Just learn Linux and write Shell scripts

Write shell scripts

There are two working modes of Shell script commands
: ➢Interactive: every time the user enters a command, it will be executed immediately
➢Batch processing: The user will write a complete Shell script in advance, and the Shell will execute many commands in the script at one time.

Write a simple script

The current system has defaulted to using Bash as the command line terminal interpreter

echo $SHELL

If you want to view the current working path and list all files and attribute information in the current directory, the script to implement this function should be similar to the following:

vim example.sh

bash example.sh

In addition to directly running the Shell script file with the Bash interpreter command above, the second way to run the script program is to execute it by entering the full path. But by default, an error message will be prompted due to insufficient permissions. At this time, you only need to add execution permissions to the script file.

./example.sh
chmod u+x example.sh
./example.sh

Receive user parameters

When the user executes a certain command, the output results are different with or without parameters:

wc -l anaconda-ks.cfg
wc -c anaconda-ks.cfg
wu -w anaconda-ks.cfg

Variables for receiving parameters have been built in, and spaces are used between variables. For example, $0 corresponds to the name of the current Shell script program, $# corresponds to the total number of parameters, $* corresponds to the parameter values ​​at all positions, $? corresponds to displaying the return value of the last command execution, and $1, $2, $3... respectively correspond to the parameter value of the Nth position, as shown in the figure.

insert image description here

vim example.sh

#!/bin/bash
echo "当前脚本名称为$0"
echo "总共有$#个参数,分别是$*。"
echo "第 1 个参数为$1,第 5 个为$5。"

bash example.sh one two three four five six


output

当前脚本名称为 example.sh
总共有 6 个参数,分别是 one two three four five six。
第 1 个参数为 one,第 5 个为 five。

Judging the user's parameters

insert image description here
Divided according to the test object, the conditional test statement can be divided into four types:
➢ File test statement;
➢ Logic test statement;
➢ Integer value comparison statement;
➢ String comparison statement.

File test is an operator that uses specified conditions to determine whether a file exists or whether permissions are satisfied, etc. The specific parameters are shown in the table.
insert image description here
The following uses the file test statement to determine whether /etc/fstab is a directory type file, and then displays the return value after the execution of the previous command through the built-in $? variable of the Shell interpreter. If the return value is 0, the directory exists; if the return value is non-zero, it means that it is not a directory, or that the directory does not exist:

[ -d /etc/fstab  ]
echo $?

Then use the file test statement to determine whether /etc/fstab is a general file. If the return value is 0, it means that the file exists and is a general file:

[ -f /etc/fstab ]
echo $?

Logical statements are used to logically analyze the test results, and different effects can be achieved according to the test results. For example, in the Shell terminal, the logical "AND" operation symbol is &&, which means that the following command will be executed after the previous command is successfully executed, so it can be used to determine whether the /dev/cdrom file exists, and if it exists, output Exist typeface

[ -e /dev/cdrom ] && echo "Exist"

In addition to the logical "and", there is also a logical "or". Its operation symbol in the Linux system is ||, which means that the following command will be executed after the previous command fails, so it can be used to combine system environment variables. USER to determine whether the currently logged-in user is a non-administrator:

echo $USER
[ $USER = root ] || echo "user"
su - linuxprobe

The third logical statement is "not", and the operation symbol in the Linux system is an exclamation mark (!), which means to take the opposite value of the judgment result in the conditional test. That is, if the result of the original test is correct, make it wrong; if the result of the original test is wrong, make it correct.

We now switch back to the root administrator status, and then determine whether the current user is a non-administrator user. Since the judgment result becomes correct due to two negations, the default information will be output normally:

exit
[ ! $user = root ] || echo "administrator"

The exclamation mark should be placed in front of the judgment statement, representing the negation operation of the entire test statement, and should not be written as "$USER != root", because "!=" represents the not equal to symbol (≠), even though the execution The effect is the same, but the logical relationship is missing, please pay more attention to this point.

We are currently logged in as the administrator user—root. The execution sequence of the following example is to first judge whether the USER variable name of the currently logged-in user is equal to root, and then use the logical "not" operator to perform the negation operation, and the effect becomes to judge whether the currently logged-in user is a non-administrator user . Finally, if the condition is true, the word user will be output according to the logic "AND" operator; if the condition is not satisfied, the word root will be output through the logic "or" operator, and the following | will be executed only when the previous && is not true | symbol.

[ ! $USER = root ] && echo "user" || echo "root"

Integer comparison operators only operate on numbers, and cannot operate numbers with strings, files, etc. Because the equal sign conflicts with the assignment command, the greater-than and less-than signs conflict with the output-redirection command and the input-redirection command, respectively. So be sure to use the canonical integer comparison operators for operations. The available integer comparison operators are shown in the table.
insert image description here

[ 10 -gt 10 ] 
echo $?

[ 10 -eq 10 ]
echo $?

The free command, which can be used to obtain information about the amount of memory currently being used and available by the system. Next, use the free -m command to check the memory usage (in MB), then use the "grep Mem:" command to filter out the remaining memory lines, and then use the awk '{print $4}' command to keep only the fourth column .

free -m
free -m | grep Mem:
free -m | grep Mem: | awk '{print $4}'

If you want to write this command into a shell script, it is recommended to assign the output result to a variable so that other commands can be called easily:

FreeMen=`free -m | grep Mem: | awk '{print $4}'`

echo $FreeMen

We use integer operators to determine whether the value of available memory is less than 1024. If it is less than 1024, it will prompt "Insufficient Memory" (insufficient memory):

[ $FreeMen -lt 1024 ] && echo "Insufficient Memory"

The string comparison statement is used to determine whether the test string is null, or whether two strings are the same. It is often used to judge whether a variable is undefined (that is, the content is empty), and it is relatively simple to understand. Common operators in string comparison are shown in the table.
insert image description here
Next, judge whether the variable is defined by judging whether the String variable is empty:

[ -z $String ]
echo $?

Try introducing logical operators again to try it out. When the environment variable value LANG used to save the current language is not English (en.US), the logical test condition is met and the words "Not en.US" (non-English) are output:

echo $LANG
[ ! $LANG = "en.US" ] && echo "Not en.US"

Guess you like

Origin blog.csdn.net/AdamCY888/article/details/131299923