Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

concatenating commands in a single line

Status
Not open for further replies.

keak

Programmer
Sep 12, 2005
247
CA
Hi there,
In *nix, we can execute multiple commands in a single line like so

command1 && command2 && command3

In the above case, if command1 fails, command 2 and 3 will not be executed.

I remember reading somewhere that there was some kind of operator that determins which command to execute depending on the outcome of command1 (faild or success).

Can't seem to google it back now .... lol
does anyone know what those operators might be?
 
humm to further define my question, what I am trying to achieve here is:

execute command1 first
if command1 succeeds, execute command2
if command1 fails, execute command3

would it be something like
command1 && command2 || command3

?
 
command1 && command2 || command3
command3 will be executed if either command1 or command2 fails.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
So this might be better suited:

if command1; then command2; else command3; fi

For an if-then-else-fi one-liner you need the semicolons or the shell will complain about the then, else and fi keywords


HTH,

p5wizard
 
What about using exit codes

command 1
if [ $? = 0 ]
then
command 2
else
command 3
fi

Mike

"A foolproof method for sculpting an elephant: first, get a huge block of marble, then you chip away everything that doesn't look like an elephant."

 
oops

Forgot the last line, recall from history and you get

echo a;if [ $? = 0 ]^Jthen^Jecho b^Jelse^J echo c^Jfi



Mike

"A foolproof method for sculpting an elephant: first, get a huge block of marble, then you chip away everything that doesn't look like an elephant."

 
Mike:

echo a;if [ $? = 0 ]^Jthen^Jecho b^Jelse^J echo c^Jfi

this is shorter:

if echo a;then echo b;else echo c;fi

There's no need for an explicit test after the first command for its returncode (unless of course you need the returncode somewhere in the then or else part), the command in itself gives a zero (true) or nonzero (false) returncode which the if responds to.


HTH,

p5wizard
 
I believe the command...
Code:
command1 && command2 || command3
...does what he wants.

Example...
Code:
$ (( 1 == 1 )) && echo True || echo False
True
$ (( 1 == 2 )) && echo True || echo False
False
Isn't that what he was asking for?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top