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?
From the bash
man page:
Aliases are not expanded when the shell is not interactive, unless the
expand_aliases
shell option is set usingshopt
(see the description ofshopt
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
).
Aliases are for the interactive shell, what you want here is a function, e.g.
#!/bin/bash
function my_command() {
echo ok
}
my_command
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With