Alias ​​doesn't work inside Bash script

I have command.sh executable

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

      

My bash terminal.

When I run it as ./command.sh

, it works great.

When I run it as /bin/bash ./command.sh

, it cannot find the executable my_command.

When I run it as /bin/sh ./command.sh

, it works great.

I'm confused here. Where is the problem?

+3


source to share


2 answers


From the bash

man page :

Aliases are not expanded if the shell is not interactive unless the shell option is expand_aliases

set with shopt

(see the description shopt

in the COMMANDS SHELL BUILTIN section below).

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

, it fails.



By default, your sh

default allows you to create aliases in scripts. When you run the script with sh

, it succeeds.

./command.sh

works because your shebang is malformed (you are missing !

in #!/bin/bash

).

+7


source


Aliases for interactive shell, what you want here is a function for example.



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

my_command

      

+2


source







All Articles