Click here to Skip to main content
15,890,527 members
Articles / Operating Systems / Linux

LINUX: Alias and Script Subshells

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Aug 2010CPOL1 min read 10.5K  
An update to my last post on Scripts and Alias

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.:

Bash
#!/bin/bash
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.

Bash
#!/bin/bash
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.

This article was originally posted at http://www.chiefsandendians.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Chiefs And Endians
United States United States
Come visit us at http://www.chiefsandendians.com

A compilation of varied technical gems learned over many years of experience in the industry.

Hint for the confused: Endian is a Computer Science term--the title is a play on words, not a misspelling.

Comments and Discussions

 
-- There are no messages in this forum --