Main Content

shell - bash. Writing conditional tests and statements - the options available

Archive - Originally posted on "The Horse's Mouth" - 2015-11-28 11:31:49 - Graham Ellis

Every language that I teach has conditionals and loops, and the bash shell is no exception. From the three day bash course given last week - an example including lots of alternative tests (but by no means all varlients!

for tests in if

  if command ... ; then
The command is run and its return status is tested.

  if [ ... ] ; then
Shell tests such as if (is it a plain file) are run

  if test ... ; then
Shell tests such as if (is it a plain file) are run (same as test)

  if [[ ... ]] ; then
String comparison / expression tested

  if (( ... )) ; then
Numeric comparison / expression tested

bash also supports lazy and and or operators (&& and ||) which can be used for shortened conditional testng based on the return status of a command - which could be one of the above bracket expressions or a reguler command:

  WomanWithCat:bash grahamellis$ grep -q main demo.c || echo yes
  WomanWithCat:bash grahamellis$ grep -q main demo.c && echo yes
  yes
  WomanWithCat:bash grahamellis$ grep -q second demo.c && echo yes
  WomanWithCat:bash grahamellis$ grep -q second demo.c || echo yes
  yes
  WomanWithCat:bash grahamellis$
  You have new mail in /var/mail/grahamellis
  WomanWithCat:bash grahamellis$ [[ 4 == 5 ]] || echo one
  one
  WomanWithCat:bash grahamellis$ [[ 4 == 5 ]] && echo two
  WomanWithCat:bash grahamellis$


(grep -q is quiet mode - supress output and just return a status)