- 此问题在此处已有答案**:
How to use aliases defined in .bashrc in other scripts?(6个答案)
两年前关闭了。
我在一个示例shell脚本中定义的别名不起作用。我是Linux shell脚本的新手。下面是示例shell文件
#!/bin/sh
echo "Setting Sample aliases ..."
alias xyz="cd /home/usr/src/xyz"
echo "Setting done ..."
在执行这个脚本时,我可以看到回显消息,但是如果我执行alias命令,我会看到下面的错误
xyz: command not found
我错过什么了吗?
7条答案
按热度按时间9cbw7uwe1#
source您的脚本,不要像
./foo.sh
或sh foo.sh
那样执行它如果像这样执行脚本,它将在子shell中运行,而不是在当前shell中运行。
对你有用。
epggiuax2#
您需要设置一个特定的选项
expand_aliases
来执行此操作:示例:
参考:https://unix.stackexchange.com/a/1498/27031和https://askubuntu.com/a/98786/127746
ttvkxqim3#
获取脚本
source script.sh
./script.sh
将在子shell中执行,所做的更改仅应用于子shell。一旦命令终止,子shell将运行,更改也将运行。或
HACK:只需在shell上运行以下命令,然后执行脚本。
要取消别名,请在shell提示符下使用以下命令
o2rvlv0m4#
如果在脚本中执行它,则别名将在脚本执行完毕时结束。
别名定义得很好,但是必须将其存储在
~/.bashrc
中,而不是shell脚本中。将其添加到该文件中,然后使用
. .bashrc
作为源代码-它将加载该文件,以便可以使用别名。只需将其写入控制台提示符。
另外:从Kent answer我们可以看到,你也可以
source
它的source your_file
。在这种情况下,你不需要使用shell script
,只是一个普通的文件将使它。chhqkbe15#
您可以使用以下命令。
dw1jzc5e6#
如果在提示符下调用别名,则别名必须位于.profile文件中,而不是脚本中。
如果您在脚本中放置了别名,则必须在脚本中调用它。
尝试运行内部具有别名的脚本时,正确答案是Source the file。
2j4z5cfb7#
将别名放在一个名为~/.bash_aliases的文件中,然后,在许多发行版中,它将自动加载,而不需要手动运行source命令来加载它。