• Uncategorized

About shell : using-alias-in-shell-script-duplicate

Question Detail

My alias defined in a sample shell script is not working. And I am new to Linux Shell Scripting.
Below is the sample shell file


echo "Setting Sample aliases ..."
alias xyz="cd /home/usr/src/xyz"
echo "Setting done ..."

On executing this script, I can see the echo messages. But if I execute the alias command, I see the below error

xyz: command not found

am I missing something ?

Question Answer

source your script, don’t execute it like ./foo.sh or sh foo.sh

If you execute your script like that, it is running in sub-shell, not your current.

source foo.sh  

would work for you.

You need to set a specific option to do so, expand_aliases:

 shopt -s expand_aliases


# With option
$ cat a
shopt -s expand_aliases
alias a="echo b"
type a
$ ./a
a is aliased to 'echo b'

# Without option
$ cat a
alias a="echo b"
type a

$ ./a
./a: line 3: type: a: not found
./a: line 4: a: command not found

cf: https://unix.stackexchange.com/a/1498/27031 and https://askubuntu.com/a/98786/127746

sourcing the script source script.sh

./script.sh will be executed in a sub-shell and the changes made apply only the to sub-shell. Once the command terminates, the sub-shell goes and so do the changes.


HACK: Simply run following command on shell and then execute the script.

alias xyz="cd /home/usr/src/xyz"

To unalias use following on shell prompt

unalias xyz 

If you execute it in a script, the alias will be over by the time the script finishes executing.

In case you want it to be permanent:

Your alias is well defined, but you have to store it in ~/.bashrc, not in a shell script.

Add it to that file and then source it with . .bashrc – it will load the file so that alias will be possible to use.

In case you want it to be used just in current session:

Just write it in your console prompt.

$ aa
The program 'aa' is currently not installed. ...
$ alias aa="echo hello"
$ aa

Also: From Kent answer we can see that you can also source it by source your_file. In that case you do not need to use a shell script, just a normal file will make it.

Your alias has to be in your .profile file not in your script if you are calling it on the prompt.

If you put an alias in your script then you have to call it within your script.

Source the file is the correct answer when trying to run a script that inside has an alias.

source yourscript.sh

Put your alias in a file call ~/.bash_aliases and then, on many distributions, it will get loaded automatically, no need to manually run the source command to load it.

You may use the below command.

shopt -s expand_aliases

source ~/.bashrc

eval $command

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.