using alias in shell script?

2019-01-11 18:46发布

问题:

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

#!/bin/sh

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 ?

回答1:

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.



回答2:

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

 shopt -s expand_aliases

Exemple:

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

# Without option
$ cat a
#!/bin/bash
alias a="echo b"
type a
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



回答3:

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.


OR

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

alias xyz="cd /home/usr/src/xyz"
./script.sh

To unalias use following on shell prompt

unalias xyz 


回答4:

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
hello
$ 

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.



回答5:

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


标签: shell