Run multiple commands in linux/bash
#############################

a few methods:
==============

NOTE: the # hash sign below means run the command

run command2 if command1 is successful (exit status 0)

# command1 && command2

run command2 if command1 fails (exit status not 0)

# command1 || command2

run command2 if command1 is successful, then run command3 if command2 is successful

# command1 && command2 && command3

run command2 if command1 is successful, then run command3 if command2 fails

# command1 && command2 || command3

run command1 and then command2 and then command3, if either command fails, the next command still runs

# command1; command2; command3;

run command1 into the background, then command2 into the background, then command3 into the background

# command1 & command2 & command3 &

see the commands status:

# jobs
# jobs -l

NOTE: you cant do: watch jobs -l  but you can do while true; do jobs -l; sleep 2; done;  why does a while loop work and watch doesnt? because watch launches a subprocess of jobs -l , and jobs -l  can only see within its same parent id. The parent id of each running job is that of the bash, and same of the jobs -l  that runs in the while loop, so they see each other and jobs -l  will see those jobs. Its the same reason jobs -l  will not see other users backgrounded jobs, and other shells backgrounded processes even if its the same user. So in a while loop jobs -l  and the backgrounded proccesses have the same parent id (the parent being bash). On the other hand jobs -l  within a watch command, has the parent of that watch command, while the backgrounded processes are that of bash, so even though they are cousins/uncles/aunts, they still cant see.

http://stackoverflow.com/questions/2500436/how-does-cat-eof-work-in-bash

Printing multiline output to a file:
=====================================

NOTE: the # hash sign below actually means that it will be a comment

cat > newscript.sh << EOF
#!/bin/bash
echo TEST
echo $PATH
echo \$PATH
echo *
echo \*
EOF

Then look at output, notice that bash will execute all of its substitutions, and if you dont want it then escape the cahracter that will cause substitution.

NOTE: the # hash sign below means run the command

# cat newscript.sh

Passing multiline output to a pipe:

cat | grep 'a' << EOF
car
bus
truck
airplane
EOF

Will output:

car
airplane

The if way:

if : ; then
command1
command2
command3
command4
fi

command1 thru 4 will run, you can put a script in command1 thru 4 and it will run that script as if your running a bash script.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *