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

查看:43
本文介绍了别名在 Bash 脚本中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an executable file command.sh

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

我的终端是 bash.

My terminal is 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 设置的(请参阅shoptSHELL BUILTIN COMMANDS 下的描述.

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!>).

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

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

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