The format of writing shell scripts with vim or VI is fixed, as follows:
#!/bin/sh#commentscode
#!
tells the system that the program specified after the path is the shell that interprets this script file. If there is no such sentence in the first line, an error will occur when executing the script file
#
comment lines until the end of this line.
Save the file as filename.sh, and then add the executable permission
chmod +x filename.sh
Examples of printing hello,world:
#!/bin/sh# the first shell script # declares a variable A and assigns a value a= "Hello,world" #将变量a的值显示的控制台上echo $a
=
variable Assignment paramname=paramvalue
Echo
echo data on the console, equivalent to SYSTEM.OUT.PRINTLN () in Java
$
reference a variable, $a refers to the variable A, you can also use ${a}, can be nested in ""
${}
referencing a variable , ${a} is the value of reference variable A, which is to avoid confusion.
#!/bin/sh# explains the difference between $ and ${} a= "Hello,world" #会查找变量as, the results show Test1,echo "Test1, $as" #会查找变量a, results show Test2,hello,worldsecho "Test2, ${a}s "
$#
Indicates the number of command-line arguments
$0,$1,... $9,${10},...
$ $ corresponds to the script name, which corresponds to the first parameter and does not show anything when there are no parameters
#!/bin/sh# number of output parameters echo "Number of parameters:" $# #输出脚本名称echo "script name:" $0# output first parameter echo "first parameter:" $
If this script is saved as a file hello.sh
[Email protected]:~/shell_ex$./hello.sh number of parameters: 0 Script name:./hello.sh first parameter: [email protected]:~/shell_ex$./hello.sh 12 Number of parameters : 1 Script Name:./hello.sh First parameter: 12
$*
List all parameters (No. $)
if [];then
...
Elif [];then
...
Else
...
fi
#!/bin/shif [$#-gt 3];then echo "The number of parameters is greater than 3" elif [$#-lt 2];then echo "The number of parameters is less than 2" else echo "parameter number is 3" fi
The commonly used test conditions are:
[-F "$file"] determine if $file is a file
[$a-lt 3] Determines whether the value of $ A is less than 3, and the same-gt and-le represent greater than or less than or equal to
[-X $file] Determines whether the $file exists and has executable permissions, and the same-R test file readability
[-N "$a"] determine if the variable $ A has a value, test the empty string with-Z
["$a" = "$b"] determine whether the value of $ A and $b are equal
[Cond1-a Cond2] to determine whether Cond1 and Cond2 are also established,-o means cond1 and Cond2 have a set up
Be aware of the spaces in the Condition Test section. there are spaces on both sides of the square brackets, and there are also spaces on both sides of the-F,-lt, =, and so on. Without these spaces, the shell would have an error explaining the script.
Shell Scripting Learning