Register
It is currently Mon Dec 22, 2014 9:17 pm

return status of a pipeline inside a conditional statement?


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Sat May 01, 2010 2:21 pm   

Joined: Fri Feb 19, 2010 4:16 pm
Posts: 3
I find I often want to have the return status from a command used in an if statement but I don't seem to be able to get the syntax correct. As an example, I'd really like to be able to combine these two following statements:

Code:
alias|grep -q '^alias which='
if [ $? = 0 ]; then unalias which; fi


into just one if statement. It seems that [ chokes on the |. What am I missing?


Top
 Profile  
 PostPosted: Sat May 01, 2010 4:17 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 579
Hi buchs,

There are many ways:
Code:
if alias -p | grep -q '^alias which='; then ...

if [ "$(alias -p | grep 'alias which=')" ]; then ... #double-quotes are needed, but not -q option

alias -p | grep -q '^alias which=' && ...

Note that none will work in scripts, because aliases are not available in them.


Top
 Profile  
 PostPosted: Sun May 02, 2010 5:53 am   

Joined: Fri Feb 19, 2010 4:16 pm
Posts: 3
Watael,

Thanks for your reply! I knew it was that easy. You've taught me several new things. I did not realize that aliases are not expanded, by default, in scripts (non-interactive). However, I see you can enable that with shopt -s expand_aliases. But, the setting/unsetting and listing of aliases occurs in either case, so the forms you gave in your reply will work in a script.

I appreciate your help.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP