Alias doesn't work inside a Bash script

2019-01-15 21:05发布

问题:

I have an executable file command.sh

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

My terminal is bash.

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

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

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

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

回答1:

From the bash man page:

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

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

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

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



回答2:

Aliases are for the interactive shell, what you want here is a function, e.g.

#!/bin/bash
function my_command() {
    echo ok
}

my_command


标签: bash sh alias