在shell脚本中使用别名?[duplicate]

nimxete2  于 2023-01-21  发布在  Shell
关注(0)|答案(7)|浏览(104)
    • 此问题在此处已有答案**:

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

我错过什么了吗?

9cbw7uwe

9cbw7uwe1#

source您的脚本,不要像./foo.shsh foo.sh那样执行它

如果像这样执行脚本,它将在子shell中运行,而不是在当前shell中运行。

source foo.sh

对你有用。

epggiuax

epggiuax2#

您需要设置一个特定的选项expand_aliases来执行此操作:

shopt -s expand_aliases

示例:

# With option
$ cat a
#!/bin/bash
shopt -s expand_aliases
alias a="echo b"
type a
a
$ ./a
# a is aliased to 'echo b'
b

# Without option
$ cat a
#!/bin/bash
alias a="echo b"
type a
a

$ ./a
./a: line 3: type: a: not found
./a: line 4: a: command not found

参考:https://unix.stackexchange.com/a/1498/27031https://askubuntu.com/a/98786/127746

ttvkxqim

ttvkxqim3#

获取脚本source script.sh

./script.sh将在子shell中执行,所做的更改仅应用于子shell。一旦命令终止,子shell将运行,更改也将运行。

HACK:只需在shell上运行以下命令,然后执行脚本。

alias xyz="cd /home/usr/src/xyz"
./script.sh

要取消别名,请在shell提示符下使用以下命令

unalias xyz
o2rvlv0m

o2rvlv0m4#

如果在脚本中执行它,则别名将在脚本执行完毕时结束。

  • 如果你想让它永久 *

别名定义得很好,但是必须将其存储在~/.bashrc中,而不是shell脚本中。
将其添加到该文件中,然后使用. .bashrc作为源代码-它将加载该文件,以便可以使用别名。

  • 如果您只想在当前会话中使用:*

只需将其写入控制台提示符。

$ aa
The program 'aa' is currently not installed. ...
$ 
$ alias aa="echo hello"
$ 
$ aa
hello
$

另外:从Kent answer我们可以看到,你也可以source它的source your_file。在这种情况下,你不需要使用shell script,只是一个普通的文件将使它。

chhqkbe1

chhqkbe15#

您可以使用以下命令。

shopt -s expand_aliases

source ~/.bashrc

eval $command
dw1jzc5e

dw1jzc5e6#

如果在提示符下调用别名,则别名必须位于.profile文件中,而不是脚本中。
如果您在脚本中放置了别名,则必须在脚本中调用它。
尝试运行内部具有别名的脚本时,正确答案是Source the file。

source yourscript.sh
2j4z5cfb

2j4z5cfb7#

将别名放在一个名为~/.bash_aliases的文件中,然后,在许多发行版中,它将自动加载,而不需要手动运行source命令来加载它。

相关问题