Characters that use double quotes
Double quotes are an important part of the shell
echo Hello echo"Hello World" Hello World
How to display: Hello "World"
is the following command OK? $ echo "Hello" World ""
Correct method: echo "Hello \" World\ ""
Condition test
Test command
Test expression or [expression]
Test command-supported conditional tests
string comparison
Arithmetic comparison
FILE-related condition testing
Logical operations
"abc"if$str"abc"then echo"The strings are equal"else echo"The strings are not equal“ fi
mkdir temp if-dthen echo"temp is a directory"fi
Conditional statements
形式if [ expression ]then statementselif [ expression ]then statementselif …else statementsfi紧凑形式; (同一行上多个命令的分隔符)
Case Statement
How many possible situations occur when Append is executed?
#!/bin/sh #脚本名: Append case $# 1 ) Cat >> $1 ;; 2 ) Cat >> $2 < $1 ;; *) echo ;; esac
21exist1notexistexist1exist2notexist2exist1notexistnotexist
SELECT statement
in itemlistdo statementsdone作用生成菜单列表
举例:一个简单的菜单选择程序#!/bin/shin Continue Finishdo case “$itemin Continue) ;; break ;; echo “Wrong choice! Please select again!” ;; esacdoneQuestion: 用while语句模拟?
Command Combination statement
分号串联command1; command2; …条件组合AND命令表 格式:statement1 && statement2 && statement3 && …OR命令表 格式:statement1 || statement2 || statement3 || …
Function call
形式func(){ statements}局部变量local关键字函数的调用func para1 para2 …返回值return
Yesno() {msg= " $"Def=" $” while true; Do Echo” ”Echo“$msg”ReadAnswerif[ “$answer” ]; Then Case“$answer”inchy| y|yes| YES)return 0;; n| N|no|no)return 1;; *)Echo“ ”Echo"Error:invalid response, expected \" Yes\ "or \" no\ "."Continue;;Esac Else return $def fi Done}
调用函数yesnoif1then :else exit1fi
Miscellaneous commands
Break: Exit from For/while/until Loop
Continue: Jumps to the next loop to continue execution
Exit N: Exit script run with exit code "n"
Return: function returns
Export: Exporting variables to the shell to make it a shell environment variable
Set: Setting parameter variables for the shell
unset: Removing a variable or function from the environment
Trap: Specifies the action to be performed after receiving the operating system signal
":" (Colon command): Empty command
“.” (Period command) or source: Executes a command in the current shell
Shell Application Examples
Write a script to implement the user management in Linux system, the specific function requirements are as follows
The script adds a new group of Class1, and then adds 30 users belonging to this group, with the user name in the form stuxx (where xx is from 01 to 30)
Key commands
Groupadd
Useradd
Mkdir
Chown
Chgrp
#!/bin/shI=1Groupadd Class1 while[$i-le -] Doif[$i-le9] ; ThenUsername=stu0${i}ElseUsername=stu${i}fiUseradd$usernamemkdir/home/$usernameChown-r$username/home/$usernameChgrp-r class1/home/$usernamei=$ (($i+1)) Done
Basic Grammar of Linux-shell programming