别名在Bash脚本中不起作用 [英] Alias doesn't work inside a Bash script

查看:71
本文介绍了别名在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).

这篇关于别名在Bash脚本中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆