This is an update to my last post on Scripts and Alias. Almost immediately after posting about the solution of enabling the expand_aliases
shell option in scripts, I tried it in a more complicated script with a subshell, and it didn't work.
I'll make this post quick. In a script, you can run commands in a subshell (remember, the script itself is already in a subshell). This sub-subshell is not really a subshell, because if you echo the $SHLVL
environment variable within it to see what shell level you are at, you will see that it is at the same level of the script. However, we are going to consider it a sub-subshell because it doesn't influence the rest of the script with what it does or sets. You run these sub-subshells by encapsulating them in parentheses. E.g.:
shopt -s expand_aliases
alias testme1="echo It Worked"
alias
testme1
( shopt -s expand_aliases
echo "I am in a subshell!"
echo "Can anyone hear me?"
alias testme2="echo Subshell Alias"
testme2 )
If you run this, you will see that testme1
works, while testme2
doesn't. Even putting the shopt -s expand_aliases
within the sub-subshell
still doesn't fix it.
SO, the solution? I went back to my old dirty hack, and that worked fine.
shopt -s expand_aliases
alias testme1="echo It Worked"
alias
testme1
( shopt -s expand_aliases
echo "I am in a subshell!"
echo "Can anyone hear me?"
alias testme2="echo Subshell Alias"
`alias | grep testme2 | cut -d\' -f2` )
One caveat to point out: If you don't have an alias set, this will mess things up. I tried running a "make
" command using my above hack, but in one case, the build environment didn't bother setting up an aliases "make
", working fine with just a standard "make
". When it tried my hack, it didn't find anything in the alias, so did nothing.
CodeProject