别名在Bash脚本中不起作用

问题描述:

我有一个可执行文件command.sh

I have an executable file command.sh

#/bin/bash
alias my_command='echo ok'
my_command

我的终端是bash。

当我像 ./ command.sh 一样运行时,它工作正常。

When I run it like ./command.sh, it works fine.

当我像 / bin / bash ./command.sh 一样运行,找不到my_command可执行文件。

When I run it like /bin/bash ./command.sh, it can't find a my_command executable.

当我像 / bin / sh ./command.sh 一样运行它时,它工作正常。

When I run it like /bin/sh ./command.sh, it works fine.

我这里很困惑。问题出在哪里?

I'm confused here. Where's the problem?

bash 手册页中:


当shell非交互式时,别名不会扩展,除非 expand_aliases shell选项是使用 shopt 进行设置(请参阅 SHELL BUILTIN COMMANDS 下的 shopt
说明

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

换句话说,默认情况下,bash shell脚本中不启用别名。当您使用 bash 运行脚本时,它将失败。

In other words, aliases are not enabled in bash shell scripts by default. When you run the script with bash, it fails.

您的 sh 似乎默认为允许脚本中使用别名。当您使用 sh 运行脚本时,它将成功。

Your sh appears to default to allowing aliases in scripts. When you run the script with sh, it succeeds.

./ command.sh 之所以起作用,是因为您的shebang格式错误(您错过了#!/ bin / bash中的! code>)。

./command.sh happens to work because your shebang is malformed (you're missing the ! in #!/bin/bash).