Executing a sequence of commands in unix shell

Created by Alin Brindusescu on 2011-02-21 03:36:59

Last week I was arguing with a work colleague about how a sequence of commands is executed. And since I haven't upgrade my memory to a 64 bits system I had a look on the internet to see if I'm right or not and then update this here as an extension to my memory.

So what is the difference between:

 
# ./configure; make; make install
 
and 
 
# ./configure && make && make install
 
and when we have to use the first or the second one.

When using ; the commands are executed one after each other without taking into account the result of the run of the previous one. So if the execution of configure fail make and make install will still be executed. So, use ; into a sequence of commands if you want all commands to be executed. For our case this dosen't make to much sense, because if configure fails then we have no reason to run make.
When using && the commands are executed one after each other but if one of the commands fail then the next on the sequence will not be executed anymore. So if the execution of configure fail then make and make install will not be executed. So, use && into a sequence of commands if there is some logical flow to be considered. For our case this make sense, because if configure fails then we have no reason to run make, or if make fails then we have no reason to run make install even if the configure ended with success.

There is one more operand ||, using this operand will cause the execution of the right side command only if the first command fails. For example

 
# ./configure || echo "Configure Fail"
 
here the echo command is executed only if the return status of configure is non zero.

All this 3 can be combined in one line but some rules should be considered otherwise the results would be unexpected.
In the following example:

 
# ./configure || echo "Configure Fail" ; cat error_log
 
the cat command is executed even if the configure command it dose not fail.
Now let's try to add the cat to our configure make sequence:
 
# ./configure && make && make install || cat error_log
 
In this sequence if configure fails then cat is executed, if configure is successful and make fails cat will still be executed and so on. If all the commands return 0 then cat will not be executed. I found this sequence very useful
The commands and the logical operators can be grouped to form more complex execution flows using {} or ().
When using {} to group the commands the commands will be executed in the current shell and when grouping with () the commands will be executed in a subshell.




Comments: work in progress!

Search

Ads