Home > shell > Linux Bash Command Chaining

Linux Bash Command Chaining

Zivo wrote a great post on the simple logic of chaining/ANDing/ORing Bash commands:

*snip*

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 run 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

*snap*

Tags:
  1. No comments yet.
  1. No trackbacks yet.