Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias doesn't work inside a Bash script [duplicate]

Tags:

alias

bash

sh

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?

like image 662
Igor Loskutov Avatar asked Dec 05 '22 21:12

Igor Loskutov


2 Answers

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

like image 197
that other guy Avatar answered Dec 31 '22 03:12

that other guy


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

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

my_command
like image 22
wich Avatar answered Dec 31 '22 04:12

wich