[Linux Basics and Shell Script] if process control statement

1. Basic syntax of if statement

1.1 How the if statement works

The if statement is the most commonly used flow control statement in Shell scripts. It is used to execute specific instructions based on specific conditions. Here's how it basically works: an if statement starts with a ifkeyword, followed by one or more conditional tests. If this conditional test is true (return value is 0), then the code block immediately following it will be executed, otherwise this code block will be skipped.

The syntax of the basic if statement is as follows:

if [condition]
then
   command1
   command2
   ...
fi

[condition]is the condition you want to test, thenfollowed by the command to execute when the condition is true.

1.2 If statement with single condition

For a single conditional if statement, you can use the following format:

if [ "$var" -gt 0 ]
then
   echo "The variable is greater than zero."
fi

In this example, the condition we are testing is whether the variable $varis greater than 0. If it is, then we output "The variable is greater than zero.".

1.3 If statements with multiple conditions

Sometimes, you may want to test multiple conditions in a single if statement. You can connect multiple conditions using logical operators -a(AND) and (OR). -oBelow is an example:

if [ "$var1" -gt 0 -a "$var2" -lt 10 ]
then
   echo "Variable values are in the correct range."
fi

In this example, the conditions we test are whether the variable $var1is greater than 0, and $var2whether the variable is less than 10. Only when both conditions are met, we will output "Variable values ​​are in the correct range."

2. if-else statement

2.1 Single conditional if-else statement

In shell scripts, if-else statements not only handle what happens when a specific condition is met, but also what happens when the condition is not met. The syntax of a basic if-else statement is as follows:

if [condition]
then
   command1
   command2
   ...
else
   command3
   command4
   ...
fi

In this syntax, if [condition]it is true (that is, the return value is 0), thenthe following commands are executed. If [condition]it is false (that is, the return value is not 0), elsethe following commands are executed.

Here is an example:

if [ "$var" -gt 0 ]
then
   echo "The variable is greater than zero."
else
   echo "The variable is not greater than zero."
fi

In this example, the condition we are testing is whether the variable $varis greater than 0. If it is, we output "The variable is greater than zero."; if not, we output "The variable is not greater than zero.".

2.2 If-else statements with multiple conditions

Like if statements, if-else statements can also handle multiple conditions. Below is an example:

if [ "$var1" -gt 0 -a "$var2" -lt 10 ]
then
   echo "Variable values are in the correct range."
else
   echo "Variable values are out of range."
fi

In this example, the conditions we test are whether the variable $var1is greater than 0, and $var2whether the variable is less than 10. Only when both conditions are met, we will output "Variable values ​​are in the correct range."; otherwise, we will output "Variable values ​​are out of range.".

3. Example explanation

In this section, we will explain the use of if and if-else statements in detail through some practical examples.

3.1 Example 1: Check whether the file exists

In this example, we will use if statement to check if a file exists.

filename="myfile.txt"

if [ -e "$filename" ]
then
   echo "The file $filename exists."
else
   echo "The file $filename does not exist."
fi

In this script, -eis a test operator that checks if the file exists. If the file exists, output information that the file exists; otherwise, output information that the file does not exist.

3.2 Example 2: Check whether the user is root

In this example, we will use if-else statement to check if the current user is root.

if [ "$EUID" -ne 0 ]
then
   echo "You are not root."
else
   echo "You are root."
fi

In this script, $EUIDis an environment variable that represents the effective user ID of the current user. If $EUIDit is not equal to 0 (that is, the current user is not the root user), output "You are not root."; otherwise, output "You are root.".

3.3 Example 3: Check whether a file is readable

In this example, we will use if statement to check if a file is readable.

filename="myfile.txt"

if [ -r "$filename" ]
then
   echo "The file $filename is readable."
else
   echo "The file $filename is not readable."
fi

In this script, -ris a test operator that checks if the file is readable. If the file is readable, information that the file is readable is output; otherwise, information that the file is unreadable is output.

3.4 Example 4: Generate file name based on date

In this example, we will use an if-else statement to generate a date-based filename.

day=$(date +%u)

if [ "$day" -eq 1 ]
then
   filename="backup_monday.tar.gz"
else
   filename="backup.tar.gz"
fi

echo "The filename is $filename."

In this script, we first use date +%uthe command to get the current date (day of the week). If today is Monday (that is, $dayequal to 1), then we set the file name to "backup_monday.tar.gz"; otherwise, we set the file name to "backup.tar.gz".

3.5 Example 5: Find files with specific extensions in a directory

In this example, we will use an if statement to find files with a specific extension in a directory.

directory="/my/directory"
extension=".txt"

files=$(ls "$directory"/*"$extension" 2> /dev/null | wc -l)

if [ "$files" != "0" ]
then
   echo "Found $files text files in $directory."
else
   echo "No text files found in $directory."
fi

In this script, we first use lscommands and pipes |to count the number of files with a specific extension in a directory. If this number is not equal to 0, then we output the number of files found; otherwise, we output the information that no files were found.

3.6 Example 6: Verify the number of command line parameters

In this example, we will use an if-else statement to verify the number of command line arguments.

if [ "$#" -ne 2 ]
then
   echo "You must enter exactly two command line arguments."
   exit 1
fi

In this script, "$#"is a special variable that represents the number of command line parameters. If the number of parameters is not equal to 2, an error message is output and exit 1execution of the script ends.

3.7 Example 7: File counting by file type

In this example, we will use if statement to count files by file type.

directory="/my/directory"
text_files=0
image_files=0

for file in "$directory"/*
do
   if [ -f "$file" ]
   then
      extension="${file##*.}"
      if [ "$extension" = "txt" ]
      then
         text_files=$((text_files+1))
      elif [ "$extension" = "jpg" -o "$extension" = "png" ]
      then
         image_files=$((image_files+1))
      fi
   fi
done

echo "Found $text_files text files and $image_files image files in $directory."

In this script, we first define two variables text_filessum image_filesto count the number of text files and image files. We then use a for loop to iterate through all the files in the directory. If the extension of a file is "txt", then we text_filesincrease the value by 1; if the extension of a file is "jpg" or "png", then we increase the image_filesvalue by 1.

3.8 Example 8: Sending notifications based on the system’s running time

In this example, we will use if-else statements to send notifications based on the system's uptime.

uptime_seconds=$(awk '{print int($1)}' /proc/uptime)

if [ "$uptime_seconds" -lt 3600 ]
then
   echo "System has been running for less than one hour."
elif [ "$uptime_seconds" -lt 86400 ]
then
   echo "System has been running for less than one day."
else
   echo "System has been running for more than one day."
fi

In this script, we first use the awk command to get the running time of the system in seconds from the /proc/uptime file. Then, we send different notifications based on this time.

3.9 Example 9: Monitoring disk space

In this example, we will use if statements to monitor disk space.

directory="/my/directory"
threshold=90

usage=$(df "$directory" | tail -1 | awk '{print $5}' | sed 's/%//')

if [ "$usage" -gt "$threshold" ]
then
   echo "Disk usage of $directory is above $threshold%."
   exit 1
fi

In this script, we first define a threshold. We then use the df command and some text processing tools to get the disk usage of the directory in percent. If the usage exceeds the threshold, a warning message is output and exit 1execution of the script ends.

3.10 Example 10: Send notification based on the existence of the process

In this example, we will use if-else statements to send notifications based on the existence of a process.

process_name="my_process"

if pgrep "$process_name" > /dev/null
then
   echo "The process $process_name is running."
else
   echo "The process $process_name is not running."
fi

In this script, we use the pgrep command to find $process_namethe process named. If the process is running, then we output a message indicating that the process is running; otherwise, we output a message indicating that the process is not running.

おすすめ

転載: blog.csdn.net/weixin_52665939/article/details/131609205