13.Linux shell programming (conditional statements and standard output redirection)

Keywords: Linux shell less

(Created in 2018/1/31)

Conditional statement

Conditional statements in the shell must end with fi, otherwise syntax error: unexpected end of file will be reported

if else then the test command here means that if the condition after test holds, then it is 0 (true), otherwise it is non-zero (false).

 #!/bin/bash
  2 
  3 var=""
  4 if test var                                                                        
  5 then 
  6 echo "success"
  7 else
  8 echo "failed"
  9 fi

if then elif then fi (equivalent to if else if statement)

  1 #!/bin/bash                                                                        
  2 
  3 if test $var
  4 then echo "success"
  5 elif test haha
  6 then echo "haha"
  7 else echo "failed"
  8 fi

Conditional statements for numeric size comparison
gt denotes greater than sign in Mathematics
The corresponding relation of other symbols is
-eq: equal to
-lt: less than
- ne: Not equal to
- le: Less than or equal to

 1 #!/bin/bash                                                                        
  2 
  3 a=10
  4 b=5
  5 
  6 if [ $a -gt $b ]      //Note that [] there must be a space in the middle, otherwise command not found will be erroneous
  7 then
  8         echo "$a is greater than $b"
  9 else
 10         echo "$a is smaller than $b"
 11 fi

String comparison

str1 == str2
str1 != str2
str1 < str2
- n str1 length is non-zero
Whether the length of-z str2 is 0

  1 #!/bin/bash
  2 
  3 str1="ren"
  4 str2="ming"
  5 str3=""
  6 str4="ren"
  7 
  8 if [ $str1 == $str4 ]                                                              
  9 then
 10         echo " str1 == str2"
 11 else
 12         echo " str1 != str2"
 13 fi
Check files or directories

- d: Check if the directory exists
- f: Check if the file exists
- e: Check whether a file or directory exists
- r: Check for presence and readability
- w: Check for existence and writability
- x: Check for existence and executability
File1-nt file2 file1 is newer than file2 (new than)
File1-ot File2 file1 is older than file2.

See if a directory exists, and if so, traverse it

   1 #!/bin/bash                                                                        
  2 
  3 dir=/usr/ndk/temp
  4 
  5 if [ -d $dir ]
  6 then
  7         echo "$dir exist"
  8         cd $dir
  9         ls
 10 else
 11         echo "$dir not exist"
 12 fi

Multiple conditional combinations

If the directory exists and the file ren.sh executable satisfies, print, traverse the dir, create a file b.sh, authorize the executable, and then traverse again

  1 #!/bin/bash                                                                        
  2 
  3 dir=/usr/ndk/temp
  4 
  5 dir2=/usr/ndk/temp/ren.sh
  6 
  7 if [ -d $dir ] && [ -x $dir2 ]
  8 then
  9         echo "find $dir and $dir2,$dir2 can be execute"
 10         ls $dir
 11         touch b.sh
 12         chmod u+x b.sh
 13         ls -la
 14 else
 15         echo "not exist"
 16 fi


  tabstop=8root@iZuf67sz57humoriy3o6oiZ:/usr/ndk/temp# ./a.sh 
find /usr/ndk/temp and /usr/ndk/temp/ren.sh,/usr/ndk/temp/ren.sh can be execute
a.sh  ren.sh
total 16
d--------- 2 root root 4096 Sep 13 07:57 .
drwxrwxrwx 7 root root 4096 Sep  7 07:47 ..
-rwxr--r-- 1 root root  215 Sep 13 07:57 a.sh
-rwxr--r-- 1 root root    0 Sep 13 07:57 b.sh
-rwxr--r-- 1 root root  115 Sep 13 07:34 ren.sh
case command in shell (similar to switch)

The format is as follows:
case variable in
pattern1) Order
pattern2) Order
* Default orders
esac

  1 #!/bin/bash                                                                        
  2 
  3 user=zhen
  4 
  5 case $user in
  6 
  7 zhen)
  8         echo "zhen is here";;
  9 ming)
 10         echo "ming is here";;
 11 *)
 12         echo "not found";;
 13 esac

for command in shell

1 #!/bin/bash
  2 
  3 list="Monday,Friday,Sonday"
  4 IFS=$,          //field separator                                                                   
  5 for item in $list
  6 do
  7         echo $item
  8 done
  9 

//The parentheses were removed from the print results.
  tabstop=8root@iZuf67sz57humoriy3o6oiZ:/usr/ndk/temp# ./c.sh 
Monday
Friday
Sonday
The while command in the shell
  1 #!/bin/bash                                                                        
  2 
  3 a=10
  4 while [ $a -gt 0 ]
  5 
  6 do
  7         echo "num:$a"
  8         a=$[ $a - 1 ]
  9 done

tabstop=8root@iZuf67sz57humoriy3o6oiZ:/usr/ndk/temp# ./d.sh 
num:10
num:9
num:8
num:7
num:6
num:5
num:4
num:3
num:2
num:1
root@iZuf67sz57humoriy3o6oiZ:/usr/ndk/temp# 

Nesting of Loop Statements and Conditional Statements

  1 #!/bin/bash                                                                        
  2 
  3 a=10
  4 while [ $a -gt 0 ]
  5 
  6 do
  7         echo "num:$a"
  8         a=$[ $a - 1 ]
  9         if [ $a -eq 5 ]
 10         then
 11                 echo "break"
 12                 break
 13         fi
 14 done

  tabstop=8root@iZuf67sz57humoriy3o6oiZ:/usr/ndk/temp# ./d.sh 
num:10
num:9
num:8
num:7
num:6
break
root@iZuf67sz57humoriy3o6oiZ:/usr/ndk/temp#

Redirecting to understand undefined in depth

Normally, each Linux command opens three files when it runs:
Standard input file (stdin): stdin file descriptor is 0, linux program reads data from stdin by default.
Standard output file (stdout): stdout file description is 1, linux program defaults to stdout output data.
Standard error file (stderr): stderr's file descriptor is 2, and linux programs write error messages to stderr streams.

After opening the file later. New file binding descriptors can be added in turn. When a shell command is executed, it inherits the file descriptor of the parent process. Therefore, all running shell commands have three default file descriptors.
Normally, command > file redirects stdout to file, and command < file redirects stdin to file.
A command was executed:
First, there is an input: input can be obtained from the keyboard or from the file.
Complete command execution: If successful, the result will be output to the screen: standard output defaults to the screen
Errors in command execution: Errors are also output to the screen: standard error s are also meant by default to the screen
If you want stderr to redirect to file, you can write as follows:

command 2> file
1

If you want stderr to append to the end of the file, you can write as follows:

command 2>> file

1. Output content to the file (automatically created if the file does not exist)

#!/bin/bash                                                                              

file=test111
echo "input into test111" > $file
 Echo "input in test 111" > $file (appended to the end of the file)

Opening the file test111 will find the result and enter two lines
input into test111
input into test111

2. Output to the screen (console)

 #!/bin/bash                                                                              

file=test111

//0 STDIN
//1 STDOUT Standard Output
//2 STDERR

echo "input into test111" >&2    //Note that there is no space between > and & 2
echo "input into test111" >&2    //Failed to output to screen

3. Control the redirection of standard output to files from the command line

Command > file redirects output to file.
Command < file redirects input to file.
Command > > file redirects the output to file in an additive manner.
N > file redirects the file with the file descriptor n to the file.
N > > file redirects the file with the file descriptor n to the file in an additional way.
N > & M merges the output files m and n.
N < & M merges the input files m and n.
<<tag takes the content between the start tag and the end tag as input.
It should be noted that file descriptor 0 is usually standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).

Command1 < infile > outfile // execute command1, read the contents from the file infile, and then write the output to the outfile
#!/bin/bash                                                                              

file=test111
echo "input into test111"
echo "input into test111"
    
//. / 14.sh &> test222 can also be exported to a file, do not understand
//Execution script

tabstop=8root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# . / 14.sh 1 > test222 //(redirect file with file descriptor n to file.) It redirects the standard output content in file 14.sh with standard output character 1 to the test 222 file, noting that any existing content in test 222 will be replaced by new content. If you want to add new content to the end of the file, use the >> operator.
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# ls
10.sh  12.sh  14.sh  3.sh  5.sh  7.sh  9.sh  ren.txt  test222
11.sh  13.sh  2.sh   4.sh  6.sh  8.sh  copy  test111
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# cat test222
input into test111
input into test111

4. Set standard output redirection in script to write to file, exec 1 > file name

#!/bin/bash                                                                              

exec 1>test333
echo "input into test333"
echo "input into test333"
      
      
//Output results:

./14.sh
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# ls
10.sh  12.sh  14.sh  3.sh  5.sh  7.sh  9.sh  ren.txt  test222
11.sh  13.sh  2.sh   4.sh  6.sh  8.sh  copy  test111  test333
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# cat test333 


  1 #!/bin/bash                                                                        
  2 
  //Redirect the standard output to the output.txt file so that all the output in the script will be
  //Printed to the output.txt file
  3 exec 1>output.txt
  //Redirect the standard error output to the error.txt file, so the error messages that occur in this file will be printed
  //Come here
  4 exec 2>error.txt
  5 
  6 echo "this is output"
  7 ls -la ffmpeg

5. Custom Output

#!/bin/bash   

//#0 STDIN Standard Input
//#1 STDOUT Standard Output
//# STDERR standard error

exec 1>file1      //Write standard output during script execution to file file1
exec 2>file2      //Export standard errors in script execution to file file2

exec 3>file3      //Custom Output Input Standard Output to file3
echo "hello" >&3
echo "byebye"
ls -a ./hehe      //Without this file, an error occurs and the error message is printed to file2
    
    
//Result:

tabstop=8root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# ./15.sh 
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# ls
10.sh  12.sh  14.sh  2.sh  4.sh  6.sh  8.sh  copy         ren.txt  STDOUT
11.sh  13.sh  15.sh  3.sh  5.sh  7.sh  9.sh  CUSTOME_STD  STDERR
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# cat STDOUT 
byebye
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# cat STDERR 
ls: cannot access './hehe': No such file or directory
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/shell# cat CUSTOME_STD 
hello

Posted by nickmgombash on Sat, 19 Jan 2019 16:06:14 -0800