Getting started with the shell

 
From the programmer's point of view, the Shell itself is a program written in C language, and from the user's point of view, the Shell is the bridge between the user and the Linux operating system. Users can either enter commands to execute, or use Shell script programming to complete more complex operations. In today's increasingly perfect Linux GUI, Shell programming still plays an important role in system management and other fields. In-depth understanding and proficient mastering of Shell programming is one of the compulsory homework for every Linux user.
 
There are many types of Linux shells, the common ones are: Bourne Shell (/usr/bin/sh or /bin/sh), Bourne Again Shell (/bin/bash), C Shell (/usr/bin/csh), K Shell ( /usr/bin/ksh), Shell for Root (/sbin/sh), etc. Different shell languages ​​have different syntax, so they cannot be used interchangeably. Each shell has its own characteristics, and basically, it is enough to master any of them. In this article, we focus on Bash, also known as Bourne Again Shell. Bash is widely used in daily work due to its ease of use and free of charge; at the same time, Bash is also the default shell of most Linux systems. In general, people do not distinguish between Bourne Shell and Bourne Again Shell, so, in the text below, we can see #!/bin/sh, which can also be changed to #!/bin/bash.
 
The format of writing shell scripts using text editors such as vi is fixed, as follows:
 
#!/bin/sh
 
#comments
 
Your commands go here
 
The symbol #! in the first line tells the system that the program specified by the following path is the shell program that interprets the script file. If the first line does not have this sentence, an error will occur when executing the script file. The subsequent part is the main program. Shell scripts, like high-level languages, also have variable assignments and control statements. Except for the first line, lines beginning with # are comment lines until the end of the line. If a line is not completed, you can add "" at the end of the line, this symbol indicates that the next line and this line will be merged into the same line.
 
After editing, save the script as filename.sh. The filename suffix sh indicates that this is a Bash script file. When executing the script, first change the properties of the script file to executable:
 
chmod +x filename.sh
 
The way to execute the script is:
 
./filename.sh
 
Let's start with the classic "hello world" and take a look at what the simplest shell script looks like.
 
#!/bin/sh
 
#print hello world in the console window
 
a = "hello world"
 
echo $a
 
Shell Script is a weakly typed language, and variables are used without first declaring their type. The new variable will be allocated memory in the local data area for storage. This variable is owned by the current Shell, and any child process cannot access the local variable. These variables are different from environment variables. Environment variables are stored in another memory area, called the user environment area. The variables in this memory can be accessed by child processes. The way to assign a variable is:
 
variable_name = variable_value
 
If you assign a value to a variable that already has a value, the new value will replace the old value. When taking a value, add $ before the variable name, and $variable_name can be used in quotation marks, which is obviously different from other high-level languages. In case of confusion, curly braces can be used to distinguish, for example:
 
echo "Hi, $as"
 
It will not output "Hi, hello worlds", but "Hi,". This is because the shell treats $as as a variable, and $as is not assigned, its value is empty. The correct way is:
 
echo "Hi, ${a}s"
 
Variables in single quotes are not subject to variable substitution.
 
Regarding variables, there are also several Linux commands that you need to know about them.
 
env is used to display variables and their values ​​in the user environment area; set is used to display variables and their values ​​in the local data area and user environment area; unset is used to delete the current value of the specified variable, which will be specified NULL; the export command is used to transfer the variables in the local data area to the user environment area.
 
Let's take a look at a more complex example. With this example, let's talk about the syntax of Shell Script.
 
 1 #!/bin/bash
 2 # we have less than 3 arguments. Print the help text:
 3 if [ $# -lt 3 ]; then
 4 cat<<HELP
 5      ren -- renames a number of files using sed regular expressions
 6
 7      USAGE: ren 'regexp' 'replacement' files
 8      EXAMPLE: rename all *.HTM files in *.html:
 9      ren 'HTM$' 'html' *.HTM
10
11 HELP
12      exit 0
13 fi
14 OLD="$1"
15 NEW="$2"
16 # The shift command removes one argument from the list of
17 # command line arguments.
18 shift
19 shift
20 # $* contains now all the files:
21 for file in $*; do
22 if [ -f "$file" ]; then
23     newfile=`echo "$file" | sed  "s/${OLD}/${NEW}/g"`
24         if [ -f "$newfile" ]; then
25             echo "ERROR: $newfile exists already"
26         else
27             echo "renaming $file to $newfile "
28             mv "$file" "$newfile"
29 fi
30 fi
31 done
 
Let's start from the beginning, the first two lines have been explained in the previous example, and starting from the third line, there is new content. Similar to other programming languages, if statements are flow control statements. Its syntax is:
 
if …; then
 
 
elif …; then
 
 
else
 
 
be
 
Unlike other languages, the conditional part of an if statement in Shell Script is separated by a semicolon. The [] in the third line represents a conditional test. Commonly used conditional tests are as follows:
 
[ -f "$file" ] Determine if $file is a file
 
[ $a -lt 3 ] Determine whether the value of $a is less than 3, also -gt and -le represent greater than or less than or equal to
 
[ -x "$file" ] Determines whether $file exists and has executable permissions, also -r tests file readability
 
[ -n "$a" ] Determine whether the variable $a has a value, test the empty string with -z
 
[ "$a" = "$b" ] Determine whether the values ​​of $a and $b are equal
 
[ cond1 -a cond2 ] Determine whether cond1 and cond2 are established at the same time, -o means that cond1 and cond2 are established
 
Note the spaces in the conditional test section. There are spaces on both sides of the square brackets, and there are also spaces on both sides of symbols such as -f, -lt, =, etc. Without these spaces, the shell would fail when interpreting the script.
 
$# represents the number of command line arguments including $0. In the shell, the script name itself is $0, and the rest are $0, $1, $2..., ${10}, ${11}, and so on. $* represents the entire parameter list, excluding $0, that is, the parameter list excluding the filename.
 
Now we understand what the third line means is if the script file has less than three arguments, execute whatever is between the if and fi statements. Then, the content from the fourth line to the eleventh line is called the Here document in Shell Script programming, and the Here document is used to pass multiple lines of text to a command. The format of the Here document starts with <<, followed by a string. When the Here document ends, this string also appears, indicating the end of the document. In this example, the Here document is output to the cat command, that is, the content of the document is printed on the screen to display help information.
 
The twelfth line of exit is a Linux command, which means to exit the current process. All Linux commands can be used in Shell scripts. Using the above cat and exit, on the one hand, skilled use of Linux commands can greatly reduce the length of Shell scripts.
 
The fourteenth and fifteenth sentences are assignment statements, which assign the first and second parameters to the variables OLD and NEW respectively. The next two sentences are comments. The function of the two shifts below the comment is to delete the first and second parameters in the parameter list, and the latter parameters become the new first and second parameters in turn. Pay attention to the parameters The list didn't originally include $0 either.
 
Then, from twenty to thirty lines is a loop statement. Loops in Shell Script have the following formats:
 
while [ cond1 ] && { || } [ cond2 ] …; do
 
 
done
 
for var in …; do
 
 
done
 
for (( cond1; cond2; cond3 )) do
 
 
done
 
until [ cond1 ] && { || } [ cond2 ] …; do
 
 
done
 
In the above loops, you can also use the break and continue statements similar to the C language to interrupt the current loop operation. The loop on line 21 puts the parameters in the parameter list into the variable file one by one. Then enter the loop to determine whether the file is a file, if it is a file, use the sed command to search and generate a new file name. sed can basically be seen as a find-replace program, reading text from standard input, such as a pipe, and outputting the results to standard output, sed uses regular expressions to search. In the twenty-third line, the function of backtick(`) is to take out the output result of the command between the two backticks. In this case, the result is taken out and assigned to the variable newfile. After that, judge whether newfile already exists, otherwise change file to newfile. So we understand the role of this script, other scripts written by Shell Script are similar, but the syntax and usage are slightly different.
 
Through this example we understand the writing rules of Shell Script, but there are a few things that need to be said.
 
First, in addition to the if statement, Shell Script also has a case statement similar to the multi-branch structure in the C language. Its syntax is:
 
houses var in
 
pattern 1 )
 
… ;;
 
pattern 2 )
 
… ;;
 
*)
 
… ;;
 
esac
 
Let's take the following example to see the usage of the case statement.
 
while getopts vc: OPTION
 
do
 
case $OPTION in
 
c) COPIES=$OPTARG
 
     ehco "$COPIES";;
 
v) echo "suyang";;
 
\?) exit 1;;
 
esac
 
done
 
The above getopts is similar to the function getopts provided by the C language. In Shell Script, getopts is often used in conjunction with the while statement. The syntax of getopts is as follows:
 
getopts option_string variable
 
option_string contains a string of single-character options. If getopts finds a hyphen in a command line parameter, it will compare the character after the hyphen with option_string. If the match is successful, set the value of the variable variable to the option. If there is no match, set the value of the variable to ? . Sometimes, the option will also have a value, such as -c5, etc. In this case, a colon should be added after the option letter in option_string. After getopts finds the colon, it will read the value, and then put the value into the special variable OPTARG middle. This command is more complicated. If necessary, the reader can refer to the relevant information written by Shell for details.
 
The function of the above loop is to take out the options after the script name in turn and process them. If an illegal option is entered, enter the part specified by "?" and exit the script program.
 
Second, Bash provides an extended select for interactive applications where the user can choose from a different set of values. Its syntax is as follows:
 
select var in …; do
 
break;
 
done
 
For example, the output of the following program is:
 
#!/bin/bash
 
echo "Your choice?"
 
select var in "a" "b" "c"; do
 
break
 
done
 
echo $ var
 
----------------------------
 
Your choice?
 
1) a
 
2) b
 
3) c
 
Third, custom functions can also be used in Shell Script, and their syntax is as follows:
 
functionname()
 
{
 
 
}
 
For example, we can put the fourth to twelfth lines in the second example above into the body of a function called help, and write help directly every time we call it later. The method of processing function call parameters in the function is to directly use the above-mentioned $1 and $2 to represent the first and second parameters respectively, and use $* to represent the parameter list.
 
Fourth, we can also debug the Shell Script script under the Shell. Of course, the easiest way is to use the echo output to view the variable value. Bash also provides a real debugging method, which is to use the -x parameter when executing the script.
 
sh ?x filename.sh
 
This will execute the script and display the values ​​of all variables in the script. You can also use the parameter -n, which does not execute the script, but returns all syntax errors.
 
Category: Linux related

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326081051&siteId=291194637