[Linux] Shell script syntax

foreword

In the Android source code, two things are inseparable, one is the .sh file, and the other is the .mk file.

Each of these two files holds a syntax, one for the Makefile syntax and one for the Shell script syntax.

These two really give me a headache, like reading a bible, woo woo woo.



1. Variables

The full variable prints:

name="乌鸡哥"
echo ${name}

Shorthand:

name="乌鸡哥"
echo $name

black chicken brother

Example:
variable
There is no namess variable at the beginning, so there is no output.

Later, I added it, and there was output.

In the end I deleted the variable namess and there was no output again.


1) Variable output length

name="乌鸡哥"
echo ${
    
    #name}

4


2) Extract the substring

The following example intercepts 4 characters from the 2nd character of the string:

string="runoob is a great site"
echo ${string:1:4} # 输出 unoo

Note: The index value of the first character is 0.


3) Find substring

Find the position of the character i or o (whichever comes first is counted):

string="runoob is a great site"
echo `expr index "$string" io`  # 输出 4

Note: ` in the above script is a backtick, not a single quote', don't get it wrong.

4) The difference between single quotes and double quotes

In shell scripts, echocommands are used to output the value of a string or variable. When using echothe command , you can use backticks, single quotes, or double quotes to surround the content you want to output.

Can you guess what the following print result is?

name="乌鸡哥"
name2='${name}'
name3="${name}"
...
echo $name
echo $name2

The result is as follows:

Brother Wuji
${name}
Brother Wuji

  1. Backticks (``): Backticks are used to enclose the command to be executed and to pass the output of the command as an argument to echothe command . For example:

    echo "Today is `date +%A`"
    

    This command date +%Awill echoinsert the output of the command into the command for output.

  2. Single quotes ('): Single quotes are used to treat the content in it as a literal value for output without any interpretation and replacement. For example:

    echo 'The value of $HOME is' $HOME
    

    This command will output The value of $HOME is /home/user, which $HOMEis treated as ordinary character output and will not be interpreted as a variable.

  3. Double quotes ("): Double quotes are used to perform operations such as variable substitution and escape parsing on the content, and output it as a whole. For example:

    name='John'
    echo "Hello, $name!"
    

    The output of this command willHello, John! be automatically replaced with the value of the variable.$name

It should be noted that when using double quotes and backquotes, if they contain unsafe characters such as special characters or spaces, proper escape processing is required to avoid unexpected errors.

单引号变量,不识别特殊语法;
双引号变量,识别特殊符号。

5) Special variables

Check whether the previous command was executed successfully.

  • $?
    • 0: success
    • 1-255: error code

Example:

insert image description here

In addition, there are several special characters used to process parameters (calling function parameters, command line parameters, etc...):

  • $*: Display all parameters passed to the script in a single string. If $*enclosed by """, all parameters will be output in the form of "$1 $2 ... $n".
  • $@: $*Same as, but used in quotes and returns each argument in quotes. If $@it is enclosed by """, use "$1" " 2 " ... " 2" ... "2"Output all parameters in the form of " n".
  • $$: The current process ID number of the script running
  • $!: ID number of the last process running in the background
  • $#: the number of parameters passed to the script
  • $-: Display the current options used by the Shell, which has the same function as the set command.
  • $?: Display the exit status of the last command. 0 means no errors, any other value indicates errors. Another function is that the return value of the function is obtained through $? after calling the function .

6) Assignment of variables in the script

  1. Every time the interpreter is invoked bash/sh, a subshell is opened, the current shell variables are not retained, and the process tree is checked through pstree. (The variable assignment in the script executed by bash is not saved)
  2. sourceOr. load the script in the current shell environment, thus preserving variables. (The variable assignment in the script executed with source will be saved)
    special case of variable

7) The variable stores the content of the command

name=ls
#显示ls
echo $name
name='ls'
#显示当前目录的文件
echo ${name}

8) Environment variables

Environment variables generally refer to exportvariables exported by built-in commands, which are used to define the operating environment of the shell and ensure the correct execution of shell commands.

The shell determines various applications such as the login user name, PATH path, and file system through environment variables. Environment variables can be temporarily created on the command line, but the variables will be lost when the user exits the shell terminal. To take effect permanently, the environment variable configuration file needs to be modified.

A remote login user-specific configuration file (local variables)

  • ~/.bash_profile(The system loads all global environment variables and shell functions first)
  • ~/.bashrc(loaded ~/.bash_profilein , which is equivalent to nesting dolls), the user will load and file when logging in~/.bash_profile~/.bashrc

Common to all users (global variable)

  • /etc/profile(system priority loading)
  • /etc/bashrc, and the system recommends that it is better to create it /etc/profile.d/instead of directly modifying the main file and modifying the global configuration file, which will affect all users who log in to the system

On Linux and Unix-like systems, global Bash Shell configuration data is usually kept in the /etc/profile and /etc/bashrc files. These files contain system-level configuration and environment variable information shared by all users.

When the operating system starts, the Bash Shell first executes the /etc/profile script to load all global environment variables and shell functions. For each new Bash terminal window, the system also automatically executes certain configuration commands in the /etc/bashrc file.

The more recommended approach is to create your own profile scripts and store them in the /etc/profile.d/ directory. This allows administrators to freely create separate configuration files to customize system-level platform and service-specific parameters without having to modify the /etc/profile or /etc/bashrc files.

For example, separate profiles could be created for each service or application and placed in the /etc/profile.d/ directory, and any .sh files in that directory would be integrated into the system-global Bash environment. Finally, every time a new Bash terminal window is started, the system will automatically execute the commands contained in these files and set the environment variables to realize the automatic configuration of the system environment.

Command to check system environment variables

  • set: Output all variables, including global variables and local variables
  • env: only show global variables
  • declare: output all variables, like set
  • export: Display and set environment variable values

Cancellation of environment variables

  • unset+ variable name, delete variable or function

set read-only variable

  • readonly: Only when the shell ends, the read-only variable becomes invalid
直接readonly 显示当前系统只读变量
[root@chaogelinux ~]# readonly name="超哥
[root@chaogelinux ~]# name="chaochao"
-bash: name: 只读变量

2. Array

One-dimensional arrays are supported (multi-dimensional arrays are not supported), and the size of the array is not limited. The subscripts of array elements start from 0.

1) Define an array

In Shell, the array is represented by brackets, and the array size does not need to be defined during initialization (similar to PHP) , and the array elements are separated by "space" symbols. The general form of defining an array is:

Array name = (value 1 value 2 ... value n)

array_name=(A B "C" D)

You can also define each component of the array separately

Array name [subscript value] = variable value

array_name[0]=value0

2) Read the array

The general format for reading the value of an array element is:

# ${数组名[下标]}
valuen=${array_name[n]}

For example:

#使用 @ 符号可以获取数组中的所有元素,例如:
echo ${array_name[@]}

#我们尝试打印一下数组元素。
array_name=(A B "C" D)

echo "第二个元素为: ${array_name[1]}"
echo "第三个元素为: ${array_name[2]}"

After printing it out, do you think there will be a difference between adding double quotes?
The answer is no, it is the same when printed out.

B
C


at last

#结合上述知识点

# 取得数组元素的个数
length=${
    
    #array_name[@]}
# 或者
length=${
    
    #array_name[*]}
# 取得数组单个元素的长度
lengthn=${
    
    #array_name[n]}

3) Associative array

declareis a shell builtin command available on Linux and other Unix-like systems. It is used to declare the type and properties of variables, and to define functions, etc. Here are some common uses of declarethe command :

  1. Declare ordinary variables
declare variable_name=value

This command will create a variable variable_namenamed and initialize it to the specified value.

  1. Declare a read-only variable
declare -r variable_name=value

This command will create a read-only variable variable_namenamed and initialize it to the specified value. The value of a read-only variable cannot be modified or reassigned.

  1. declare integer variable
declare -i variable_name=value

This command will create an integer variable variable_namenamed and initialize it to the specified value. If the variable is subsequently assigned a non-integer value, the system will try to automatically convert it to an integer.

  1. declare array variable
declare -a array_name

This command will create an array variable array_namenamed . In subsequent operations, array subscripts can be used to access and assign array elements.

  1. Declare an associative array variable
declare -A associative_array_name

This command will create an associative array variable associative_array_namenamed . In subsequent operations, any string can be used as an array subscript to access and assign values ​​to array elements.

  1. declare function
declare -f function_name

This command will print the definition of the function function_namenamed . If no parameters are added, all defined functions will be listed.

In addition to the above usage, declarethe command also supports some other options and parameters, and you can view their detailed descriptions through help declarethe command .

We detail the fifth point here

In the Bash shell, an associative array is a special type of array that uses arbitrary strings as subscripts to access and assign array elements. Associative arrays are also known as hash tables, dictionaries, or maps.

To declare an associative array variable, declareuse -Athe option of the command, for example:

declare -A my_array

It can also be defined directly like this:

declare -A my_array=(["name"]="John" ["age"]="30")

Here, we use the associative array subscripts "name"and "age"to assign values ​​to the array elements respectively.

my_array["name"]="John"
my_array["age"]=30

In subsequent operations, you can use any string as an array subscript to access and assign array elements, for example:

echo "My name is ${my_array["name"]} and I am ${my_array["age"]} years old."

Print all values ​​of an array:

# 两者等效
echo "数组的元素为: ${my_array[*]}"
echo "数组的元素为: ${my_array[@]}"

The elements of the array are: John 30

Print all keys of an array:

echo "数组的键为: ${
     
     !site[*]}"
echo "数组的键为: ${
     
     !site[@]}"

The keys of the array are: name age

Print the number of elements in an array:

echo "数组元素个数为: ${
     
     #my_array[*]}"
echo "数组元素个数为: ${
     
     #my_array[@]}"

The number of array elements is: 2

Note that in an associative array, each element is associated with a separate string key. Therefore, when accessing array elements, any legal string can be used as a subscript, including empty strings, special characters, and spaces. Unlike ordinary arrays, associative arrays do not need to specify the length of the array in advance, nor do they need to initialize the array elements at definition time.


3. Notes

# 别学习了 好好睡觉(单行注释)
# 多行注释(Here Document)
: <<END_COMMENT
注释内容...
注释内容...
注释内容...
END_COMMENT
# 举个栗子
# 这段代码先执行 Here Document (<<)语法结构,可以看成标准输入
# 将内容传递给 cat 命令作为标准输入
# 然后再将 cat 命令的输出结果重定向(>)到文件中
# 最终将字符串 "五级五级" 和 "66666666" 写入到 77.sh 文件中。
cat > device/$1/$2/vendorsetup.sh << EOF
echo "五级五级"
echo "66666666"
EOF

4. Operator

1) Arithmetic operators

It is addition, subtraction, multiplication and division and so on.

Conditional expressions should be placed between square brackets, and there must be spaces, for example: [$a==$b]is wrong, must be written as [ $a == $b ].

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
   echo "a 等于 b"
fi
if [ $a != $b ]
then
   echo "a 不等于 b"
fi

2) Relational operators

Relational operators only support numbers, not strings, unless the value of the string is a number.

  • -eq:equal
  • -ne:not equal
  • -gt: the left is greater than the right
  • -lt: the left is smaller than the right
  • -ge: the left is greater than or equal to the right
  • -le: the left is less than or equal to the right
a=10
b=20

if [ $a -eq $b ]
then
   echo "$a -eq $b : a 等于 b"
else
   echo "$a -eq $b: a 不等于 b"
fi
if [ $a -ne $b ]
then
   echo "$a -ne $b: a 不等于 b"
else
   echo "$a -ne $b : a 等于 b"
fi
if [ $a -gt $b ]
then
   echo "$a -gt $b: a 大于 b"
else
   echo "$a -gt $b: a 不大于 b"
fi
if [ $a -lt $b ]
then
   echo "$a -lt $b: a 小于 b"
else
   echo "$a -lt $b: a 不小于 b"
fi
if [ $a -ge $b ]
then
   echo "$a -ge $b: a 大于或等于 b"
else
   echo "$a -ge $b: a 小于 b"
fi
if [ $a -le $b ]
then
   echo "$a -le $b: a 小于或等于 b"
else
   echo "$a -le $b: a 大于 b"
fi

3) Boolean operators

  • !:No
  • -o:or
  • -a:and
a=10
b=20

if [ $a != $b ]
then
   echo "$a != $b : a 不等于 b"
else
   echo "$a == $b: a 等于 b"
fi
if [ $a -lt 100 -a $b -gt 15 ]
then
   echo "$a 小于 100 且 $b 大于 15 : 返回 true"
else
   echo "$a 小于 100 且 $b 大于 15 : 返回 false"
fi
if [ $a -lt 100 -o $b -gt 100 ]
then
   echo "$a 小于 100 或 $b 大于 100 : 返回 true"
else
   echo "$a 小于 100 或 $b 大于 100 : 返回 false"
fi
if [ $a -lt 5 -o $b -gt 100 ]
then
   echo "$a 小于 5 或 $b 大于 100 : 返回 true"
else
   echo "$a 小于 5 或 $b 大于 100 : 返回 false"
fi

4) Logical operators

a=10
b=20

if [[ $a -lt 100 && $b -gt 100 ]]
then
   echo "返回 true"
else
   echo "返回 false"
fi

if [[ $a -lt 100 || $b -gt 100 ]]
then
   echo "返回 true"
else
   echo "返回 false"
fi

5) String operators

a="abc"
b="efg"

#检测两个字符串是否相等,相等返回true
if [ $a = $b ]
then
   echo "$a = $b : a 等于 b"
else
   echo "$a = $b: a 不等于 b"
fi
#检测两个字符串是否不相等,不相等返回true
if [ $a != $b ]
then
   echo "$a != $b : a 不等于 b"
else
   echo "$a != $b: a 等于 b"
fi
#检测字符串长度是否为0,为0返回true
if [ -z $a ]
then
   echo "-z $a : 字符串长度为 0"
else
   echo "-z $a : 字符串长度不为 0"
fi
#检测字符串长度是否不为0,不为0返回true
if [ -n "$a" ]
then
   echo "-n $a : 字符串长度不为 0"
else
   echo "-n $a : 字符串长度为 0"
fi
#检测字符串是否不为空,不为空返回true
if [ $a ]
then
   echo "$a : 字符串不为空"
else
   echo "$a : 字符串为空"
fi

6) File test operator

The file test operators are used to test various attributes of Unix files.

1

file="/var/www/runoob/test.sh"
if [ -r $file ]
then
   echo "文件可读"
else
   echo "文件不可读"
fi

5. Input and output

1) read(input)

read -p "input your name:" str
echo "read name: $str"  

2) echo (output)

echo `date`

3) printf(output)

Format specification:

printf  format-string  [arguments...]

Parameter Description:

  • format-string: is the format control string
  • arguments: is a list of parameters

Take a chestnut:

printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg 
  • %-10s: Refers to a width of 10 characters (- means left alignment, no means right alignment), any character will be displayed within the 10-character width, if it is insufficient, it will be automatically filled with spaces, if it exceeds, the content will be displayed in its entirety come out.
  • %-4.2f: Refers to formatting as a decimal, where .2refers to retaining 2 decimal places
  • %s: output a string
  • %d: integer output
  • %c: output a character
  • %f: Output real numbers, output in decimal form
# format-string为双引号
printf "%d %s\n" 1 "abc"

# 单引号与双引号效果一样
printf '%d %s\n' 1 "abc"

# 没有引号也可以输出(没换行)
printf %s abcdef

# 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用(没换行)
printf %s abc def

printf "%s\n" abc def

printf "%s %s %s\n" a b c d e f g h i j

# 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替
printf "%s and %d \n"

1 abc
1 abc
abcdefabcdefabc
def
a b c
d e f
g h i
j
and 0

Special usage of printf

1


6. Process control

1)if

Normal format:

if 条件1
then
    命令1 
    命令2
    ...
    命令N 
fi

Shorthand for a one-line pattern:

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi

Multiple if-elseif-else patterns:

if 条件1
then
    命令1
elif 条件2 
then 
    命令2
else
    命令N
fi

In the ["$a" -gt "$b"]judgment use -gt for greater than, and -lt for less than. In the judgment
condition of if else, > and < can be used directly for greater than and less than. The if else statement is often used in conjunction with the test command.((a>b))

Special: test command

testA command is a built-in command used to test conditions in the Bash shell, and is usually used for judgment and branching of the control process.

There are many forms of the test command, the most basic syntax is as follows:

test+选项+expression

or

[选项+expression ]

Here expressionrepresents a specific test condition, which can be different types of operations such as file test, string comparison, and number comparison.

testThe command has various options that can be used to test conditions, here are some of the more common options:

  • -n string: Determine whether the string is not empty.
  • -z string: Determine whether the string is empty.
  • -f file: Determine whether the file exists and is an ordinary file.
  • -e file: Determine whether the file exists.
  • -d file: Determine whether the file exists and is a directory.
  • -r file: Determine whether the file exists and is readable.
  • -w file: Determine whether the file exists and is writable.
  • -x file: Determine whether the file exists and is executable.
  • -s file: Determine whether the file exists and is not empty.

These options can be used to combine different types of conditional expressions, and cooperate with logical operators (such as &&, ||) to realize complex control flow. For example:

filename="example.txt"

if test -f "$filename" && test -r "$filename"; then
  echo "yes"
else
  echo "no"
fi

#或者

if [ -f "$filename" ] && [ -r "$filename" ]; then
  echo "yes"
else
  echo "no"
fi

#或者

if [ -f example.txt ] && [ -r example.txt ]; then
  echo "yes"
else
  echo "no"
fi

#或者
#这里使用-a选项(即逻辑与)连接两个表达式,表示需要同时满足多个条件。
if [ -f example.txt -a -r example.txt ]; then
  echo "yes"
else
  echo "no"
fi

This example checks to see if the file myfileexists and is readable, and outputs "yes" if both conditions are true, and "no" otherwise.

It should be noted that all parameters accepted in the test command must be placed in square brackets, each parameter must be separated by a space, and there must be a space or other separator between the last parameter and the square brackets.

It should be noted that square brackets [] can be used instead of the test command in the bash shell to achieve the same effect. [ -f file.txt ]That's why the example above uses .


2)for

General format:

for var in item1 item2 ... itemN
do
    命令1
    命令2
    ...
    命令N
done

Shorthand for a one-line pattern:

for var in item1 item2 ... itemN; do 命令1; 命令2… done;
for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done
#!/bin/bash

for str in This is a string
do
    echo $str
done

This
is
a
string


3)while

General format:

while 条件
do
    # 可以在这里添加自己的命令
done
#!/bin/bash
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done
echo '按下 <CTRL-D> 退出'
echo -n '输入你最喜欢的网站名: '
while read FILM
do
    echo "是的!$FILM 是一个好网站"
done

In a Linux terminal, pressing the Ctrl+d keys performs the following different functions, depending on the context of the current terminal:

  1. End of input flag: When you want to exit from the terminal input stream, press Ctrl+d to indicate the end of input. For example, when piping (|) output to a command or file on the command line, you can press Ctrl+d to complete input and start processing.

  2. Terminate a foreground process: If you are running a foreground process and want to force stop it, you can use the Ctrl+d key combination to send a SIGINT signal. This signal tells the application to stop the current operation and any ongoing data processing, and to exit the process.

  3. Log out of the current user: In most Linux systems, press Ctrl+d to log out of the currently logged in user. This is typically used with shell or other CLI applications.

In conclusion, Ctrl+d does various things depending on the terminal context you are currently using. When using it, please be aware of the meaning attached to it and handle it with care.

Infinite loop:

while :
do
    # 可以在这里添加自己的命令
done


while true
do
    # 可以在这里添加自己的命令
done


for (( ; ; ))
do
   echo "loop will run forever unless you terminate it with Ctrl+c"
   # 可以在这里添加自己的命令
done


4)until

until Loop executes a sequence of commands until a condition is true and stops.
The until loop is the exact opposite of the while loop.

until 条件
do
    # 可以在这里添加自己的命令
done
a=0
# 输出0-9
until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

5)case

Value can be variable or constant

General format:

casein
模式1)
    command1
    command2
    ...
    commandN
    ;;
模式2)
    command1
    command2
    ...
    commandN
    ;;
esac
echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac
site="runoob"

case "$site" in
   "runoob") echo "菜鸟教程"
   ;;
   "google") echo "Google 搜索"
   ;;
   "taobao") echo "淘宝网"
   ;;
esac

6)break和continue

End the loop and jump out of a loop. Same as Java


7. Function

The linux shell can user-defined functions, and then they can be called casually in shell scripts.

All functions must be defined before use. This means that the function must be placed at the beginning of the script until it is first seen by the shell interpreter before it can be used. A function is called using only its function name.

1) Function return value

funWithReturn(){
    
    
    echo "这个函数会对输入的两个数字进行相加运算..."
    echo "输入第一个数字: "
    read aNum
    echo "输入第二个数字: "
    read anotherNum
    echo "两个数字分别为 $aNum$anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "输入的两个数字之和为 $? !"

The return value of the function is obtained through $? after calling the function.

2) Functions with parameters

funWithParam(){
    
    
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

Note: $10The tenth parameter cannot be obtained, it is required to obtain the tenth parameter ${10}. When n>=10, you need to use ${n}to get the parameters.


8. Input and output redirection

It is to get the content of the file over, or get it over.

1) Output redirection

Put the word Wujige into this 77.txt file

$ echo "乌鸡哥" > 77.txt

2) Input redirection

wc -l < 文件名

Among them, wcis a command for counting text information, and -lthe parameter indicates that only the number of lines is counted. <The notation indicates that the contents of the file are passed as input to the command.

Therefore, after executing this command, it will read the content of the file "users", count the number of lines in it, and output the result. This command is often used to check the line count of a file in a Unix or Linux environment.


sort < input.txt > output.txt

From input.txtreading the file, then sortsorting it, and finally outputting it after finishing it output.txt.


3) Special redirection

  • Standard input file (stdin): The file descriptor of stdin is 0, and Unix programs read data from stdin by default.
  • Standard output file (stdout): The file descriptor of stdout is 1, and Unix programs output data to stdout by default.
  • Standard error file (stderr): The file descriptor of stderr is 2, and the Unix program will write error information to the stderr stream.
ls /mnt 2>> log.txt

This command attempts to list the contents of the /mnt directory. If the operation is successful, the result will be printed directly to the terminal; however, if the operation fails, the command will record the relevant error information, and write the error information into the log.txt file by appending. This redirection technique is especially useful when you want to take the output and save it in a file.

ls /mnt > output.txt 2>&1

This command attempts to list all the contents of the /mnt directory. If the directory is accessible, the command outputs the results in a listing format to the file output.txt, regardless of whether the results are output to standard output or standard error. If there are any errors or warnings, they will also be redirected into this file, allowing you to easily and quickly see all output. Note, when using this syntax, make sure you have sufficient permissions to access the input and output files, and do not overwrite or modify accidental files.


4)Here Document

Here Document is a syntax used in Bash/Shell scripts to provide input to commands. It allows you to specify a "qualifier" (also known as a delimiter) after which multiple lines of text below that delimiter are processed as the command's standard input.

In scripting, Here Document syntax typically takes the following form:

command <<LIMITER
input text
...
LIMITER

in:

  • command represents the command to receive a Here Document as input.
  • The << symbol is used to specify the Here Document delimiter, and leave it blank to allow the shell to automatically choose a default.
  • LIMITER is a user-specified delimiter that isolates input text and tells the shell when to stop reading standard input.
  • input text is the multiline text that is ultimately passed to the command as standard input.

Note that the delimiter must start from the first column, so the text in the Here Document cannot be indented. Also, when you need to use variables or other Bash commands in the input text, you can precede the qualifier with a "-" sign, for example, which tells the <<-LIMITERshell to ignore indentation in the input text (like a heredoc in Bash mark).

For example, here's an example using the Here Document syntax:

cat <<END
This is some example text that will be passed
as standard input to the cat command.
It can contain multiple lines.
END

This will create a delimiter named END (END can be replaced with pp or whatever), and pass three lines of text as standard input to the cat command. Eventually, the command will print the input text to the terminal as output.


5) /dev/null file

If you want to execute a command without displaying the output on the screen, you can redirect the output to /dev/null:

$ command > /dev/null

/dev/null is a special file that writes to it are discarded; if you try to read from it, nothing will be read. But the /dev/null file is very useful. Redirecting the output of a command to it will have the effect of "disabling output".

If you want to shield stdout and stderr, you can write like this:

$ command > /dev/null 2>&1

Note: 0 is standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).

There can be no space between 2 and > here, and only when 2> is one, it means error output.


9. File contains (reference)

Similar to the C language, you can also refer to functions, variables, etc. in other .sh scripts.

. filename   # 注意点号(.)和文件名中间有一空格


source filename

Create two shell script files

A.sh file

#!/bin/bash
name="乌鸡哥"

B.sh file

#!/bin/bash
#使用 . 号来引用test1.sh 文件
. ./test1.sh

# 或者使用以下包含文件代码
# source ./test1.sh

echo "${name}"

$ chmod +x B.sh
$ ./B.sh
Wujige

The included file A.sh does not need executable permission.

Guess you like

Origin blog.csdn.net/qFAFAF/article/details/130125945