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
Bash Example 1.
- if [ “foo” = “foo” ]; then
- echo expression evaluated as true
- 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)
- if grep -q root /etc/passwd; then
- echo account root exists
- else
- echo account root not exist
- 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.
- T1=“foo”
- T2=“bar”
- if [ “$T1” = “$T2” ]; then
- echo expression evaluated as true
- else
- echo expression evaluated as false
- 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
- #!/bin/sh
- if [ “$#” != “1” ]; then
- echo “usage: $0 <file>”
- exit 1
- 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.
- if [ “foo” = “foo” ]; then
- echo expression evaluated as true
- else
- echo expression evaluated as false
- 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)
- if [ -e myfile ]; then
- echo myfile exists
- else
- touch myfile
- echo myfile created
- 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
- echo 1 >file1
- echo 2 >file2
- if ! diff -q file1 file2; then
- echo file1 file2 diff
- else
- echo file1 file2 same
- 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 ~]#