User Tools

Site Tools


bash:run_a_program_or_script:run_a_bunch_of_commands_in_sequence

BASH - Run a program or script - Run a bunch of commands in sequence

To run a bunch of commands just put semicolons between the commands:

date ; free; date

returns:

Thu  4 Feb 13:30:42 GMT 2021
              total        used        free      shared  buff/cache   available
Mem:       65872344     7039056    47427116      929180    11406172    57177400
Swap:        999420           0      999420
Thu  4 Feb 13:30:42 GMT 2021

NOTE: As can be seen the same command can be run multiple times.

Here the date command is run twice.


ALERT: Running commands in sequence can be bad.

For example:

cd /foo; rm *

NOTE: The idea here is to erase all the files in directory foo (but not sub-directories; -r is needed for that).

But what if the cd fails? Then all the files in the current directory will be erased instead. Not good!

Far better to use:

cd /foo && rm *

NOTE: The && is just like in C; this is the AND operator.

Nearly all BASH programs return a 0 error status for true and anything else is false.

  • That allows programmers to return an error code for failure and which returns a false.

To test, this rather use the following (which does not include the rm for safety).

cd /foo && ls   # Not rm so we don't do anything bad by mistake.

If /foo exists, the cd command will return 0 which is true.

  • That means the result of the AND could be true and therefore execution continues with the ls.
  • However, if the cd fails, the result will be false.
  • If any input to an AND function is false, the other values does not matter.
  • Therefore, as soon as anything returns false, the whole thing stops.
  • So if there is no /foo, the ls command will not execute at all.

OR

There is also an OR operator || that quits as soon as anything returns true.

grep "dummy" /etc/passwd || echo No such user

NOTE: Try this command using an actual user instead of dummy to see what is returned when this succeeds.

bash/run_a_program_or_script/run_a_bunch_of_commands_in_sequence.txt · Last modified: 2023/06/09 18:08 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki