View on GitHub

Computational Techniques for Life Sciences

IF/THEN/ELSE

Purpose

IF statements test if a condition is met.

Syntax

if [test condition]
then ACTIONS
elif [OTHER TESTS]
  OTHER_ACTIONS
else OTHER_ACTIONS
fi

OR

if [test condition]; then ACTIONS ; elif [OTHER TESTS]; OTHER ACTIONS; else OTHER_ACTIONS ; fi
prompt> a=apple
prompt> if  [[ $a == "pear" ]] ; then echo "MATCH" ; else echo "NO-MATCH"; fi
NO-MATCH
prompt> a=pear
prompt> if  [[ $a == "pear" ]] ; then echo "MATCH" ; else echo "NO-MATCH"; fi
MATCH

Common test conditions:

Strings and Arithmetic
Operator Meaning
String Comparison
= Equal to
== Equal to
!= Not equal to
< Less than (ASCII)
> Greater than (ASCII)
-z String is empty
-n String is not empty
   
Arithmetic Comparison
-eq Equal to
-ne Not equal to
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
   
Arithmetic Comparison within double parentheses (( … ))\
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
File tests
Operator Tests Whether Operator Tests Whether
-e File exists -s File is not zero size
-f File is a regular file    
-d File is a directory -r File has read permission
-h File is a symbolic link -w File has write permission
-L File is a symbolic link -x File has execute permission
-b File is a block device    
-c File is a character device -g sgid flag set
-p File is a pipe -u suid flag set\
-S File is a socket -k “sticky bit” set
-t File is associated with a terminal    
       
-N File modified since it was last read F1 -nt F2 File F1 is newer than F2
-O You own the file F1 -ot F2 File F1 is older than F2
-G Group id of file same as yours F1 -ef F2 Files F1 and F2 are hard links to the same file

! “NOT” (reverses sense of above tests)

Exercises

Write a script that reads the first two arguments from the command line, a filename and a number. If the file exists and the number is negative, change the permissions on the file to read-only (r--). If the file doesn’t exist or if the number is greater than 50, then create the file and change it’s permissions to rwx.

vi file_num.sh
#!/bin/bash

file=$1
value=$2
negcutoff=0
poscutoff=50

if [ -r $file ]
then
  if [ $value -lt $negcutoff ]
  then
    chmod 400 $file
  elif [ $value -gt $poscutoff ]
   then
     chmod 700 $file
  fi
else
  touch $file
  chmod 700 $file
fi
prompt> ./file_num.sh fake.txt 70; ls -l fake.txt ;
0 -rwx------  1 beckbw  staff  0 Jul 16 18:59 fake.txt


Prev LOOPS | Next WHILE LOOPS | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center