BASH Shell Command Chaining

por | 21 agosto, 2008

###BASH Command Chaining/Logical ANDing/ORing###

Command Chaining:

TO run a -> b -> c

ls -lF /etc; pwd;who;ps


Logical ANDing:

Program b will execute only if program a was executed
a&&b&&c

Programs mutually inclusive
Returns a exit status 0 and then run b exit status 0 and then run C

Logical ANDing – runs subsequent based on exit status of 0

ls -l /etc/resolv.conf && grep name /etc/resolv.conf


Logical ORing:

Run subsequent program based on failure of previous

ls -l /etc/resolve.conf || grep name /etc/resolv.conf

Example:

If the file text.txt doesnt exist you can create with ORing

ls -l test.txt || touch test.txt

Combining ANDing ORing

-bash-3.00$ ls -l text.txt || touch test.txt && ls -ltr test.txt
text.txt: No such file or directory
-rw-r--r-- 1 carlosap other 0 Aug 22 00:13 test.txt


BASH for LOOPS

text.txt
1
2
3

LOOPS SYNTAX:
for variable in list; do command variable; done


-bash-3.00$ for i in `cat test.txt`; do echo $i; done
1
2
3
-bash-3.00$ for i in `cat test.txt`; do echo test$i; done
test1
test2
test3