Conditional statements in the Shell, similar with other programming languages.

If you want to know what are the conditions, obtained by man test can help.

Common formats

22

Bash Example 1.




  1. if [ “foo” = “foo” ]; then
  2.     echo expression evaluated as true
  3. fi

[root@dll ~]# if [ “foo” = “foo” ]; then
>     echo expression evaluated as true
> fi
expression evaluated as true
[root@dll ~]#

Bash Example 2: bash if -q (Determine whether the file contains a string)




  1. if grep -q root /etc/passwd; then
  2.     echo account root exists
  3. else
  4.     echo account root not exist
  5. fi

[root@dll ~]# if grep -q root /etc/passwd; then
>     echo account root exists
> else
>     echo account root not exist
> fi
account root exists
[root@dll ~]#

Bash Example 3.

  1. T1=“foo”
  2. T2=“bar”
  3. if [ “$T1” = “$T2” ]; then
  4.     echo expression evaluated as true
  5. else
  6.     echo expression evaluated as false
  7. fi

[root@dll ~]# T1=”foo”
[root@dll ~]# T2=”bar”
[root@dll ~]# if [ “$T1” = “$T2” ]; then
>     echo expression evaluated as true
> else
>     echo expression evaluated as false
> fi
expression evaluated as false
[root@dll ~]#

Bash Example 4:  Judge number of command line parameters

file  if_4.sh

  1. #!/bin/sh
  2. if [ “$#” != “1” ]; then
  3.     echo “usage: $0 <file>”
  4.     exit 1
  5. fi

[root@smsgw root]# cat if_4.sh
#!/bin/sh

if [ “$#” != “1” ]; then
echo “usage: $0 <file>”
exit 1
fi

[root@smsgw root]# chmod +x if_4.sh
[root@smsgw root]# ./if_4.sh
usage: ./if_4.sh <file>
[root@smsgw root]# ./if_4.sh hello
[root@smsgw root]#

Bash Example 5.

  1. if [ “foo” = “foo” ]; then
  2.     echo expression evaluated as true
  3. else
  4.     echo expression evaluated as false
  5. fi

[root@dll ~]# if [ “foo” = “foo” ]; then
>     echo expression evaluated as true
> else
>     echo expression evaluated as false
> fi
expression evaluated as true
[root@dll ~]#

Bash Example 6:  bash if -e  (Determines whether the file exists)

  1. if [ -e myfile ]; then
  2.     echo myfile exists
  3. else
  4.     touch myfile
  5.     echo myfile created
  6. fi

[root@dll ~]# if [ -e myfile ]; then
>     echo myfile exists
> else
>     touch myfile
>     echo myfile created
> fi
myfile created
[root@dll ~]# if [ -e myfile ]; then
>     echo myfile exists
> else
>     touch myfile
>     echo myfile created
> fi
myfile exists
[root@dll ~]# ls -l myfile
-rw-r–r– 1 root root 0 10-09 20:44 myfile

Bash Example 7: Determine whether two files are the same

  1. echo 1 >file1
  2. echo 2 >file2
  3. if ! diff -q file1 file2; then
  4.     echo file1 file2 diff
  5. else
  6.     echo file1 file2 same
  7. fi

[root@dll ~]# echo 1 >file1
[root@dll ~]# echo 2 >file2
[root@dll ~]# if ! diff -q file1 file2; then
>     echo file1 file2 diff
> else
>     echo file1 file2 same
> fi
Files file1 and file2 differ
file1 file2 diff
[root@dll ~]#