perjantai 3. huhtikuuta 2015

Linux > Bash > shopt (expand_aliases)

Problem:
I am currently coding some Bash scripts to install Hadoop on Aalto University's Triton SLURM system through SBATCH. Bash script running through SBATCH can't recognize my own aliases, whereas the same alias, which I created, can be recognized by running though Triton's front end or our school's kosh host

Investigation:
My initial wrong guess at the beginning: the SLURM system just don't support aliases
Why my guess is wrong: after Googling with keyword - bash display all aliases, I found the link:
http://stackoverflow.com/questions/948008/linux-command-to-list-all-available-commands-and-aliases
There is command: "compgen -a" will list all the aliases you could run. 
Then I run the following commands:
alias alias_test='echo "hello world"'
alias_test
compgen -a
In the stdout log, "compgen -a" indeed listed the aliases, but in the stderr log I got error message like: /var/spool/slurmd/job17374903/slurm_script: line 25: alias_test: command not found

Second guess: There must be some settings on SLURM, which makes my aliases not recognizable.
Research: I read page: http://tldp.org/LDP/abs/html/aliases.html. Surprisingly I found in their alias making example, there is an extra line:  shopt -s expand_aliases
Then I read shopt's manual (man shopt): 
option -s means: Enable (set) each optname.
Reasoning of my second guess: command shopt -s expand_aliases enables the expand_aliases, then I tried to add this line at the beginning of my previous code like:
shopt -s expand_aliases
alias alias_test='echo "hello world"'
alias_test
compgen -a
Now my alias can be recognized!

Moreover, at beginning of shopt manual, there is text: At the beginning of manual:
"Toggle  the  values  of  variables controlling optional shell behavior.  With no options, or with the -p option, a list of all settable options is displayed, with an indication of whether or not each is set.  The -p option causes output to be displayed in a form that may be reused as input.  Other options have the following meanings:"
Then I added shopt -p to previous code:
shopt
shopt -s expand_aliases
echo "after expand_aliases enabled"
shopt
alias alias_test='echo "hello world"'
alias_test
compgen -a
Then ran it through sbatch:
the log before text "after expand_aliases enabled" displayed: expand_aliases off
the log after    text "after expand_aliases enabled" displayed: expand_aliases on

=> solution: add "shopt -s expand_aliases" at the beginning of the Bash script!