Shell programming loop statements and functions
An echo statement
1.1 Echo commonly used escape characters
Echo -n means output without line
breaks. Echo -e outputs escape characters and outputs the escaped content to the screen
Common escape characters | Paraphrase |
---|---|
\b | After escaping, it is equivalent to pressing the backspace key (backspace), but the premise is that there are characters after "\b"; "\b" means deleting the previous character, and "\b\b" means deleting the first two characters. |
\c | Output without line break. When there are no characters after "\c", the effect is equivalent to echo -n; But when there are still characters after "\c", the characters after "\c" will not be output. |
\n | Line feed, the characters to be output start on a new line from "\n". |
\v or \f | Line break, but the beginning of the new line after the line break is connected to the end of the previous line |
\t | Means to insert tab, that is, horizontal tab; |
\r | The cursor moves to the beginning of the line, but does not wrap, which is equivalent to using the characters after "\r" to overwrite the characters of the same length before "\r", but when there is no character after "\r", the one before "\r" Characters will not be overwritten |
\\ | Means to insert "\" itself |
Operation example
1.2 Calculation method
There are 4 calculation methods in shell script
1. i=$(expr 12 \* 5)
2. i=$((12*5))
3. i=$[12*5]
4. let i= 12*5
i++相当于i=$[$i+1]
i--相当于i=$[$i-1]
i+=2相当于i=$[$i+2]
Two loop statement
2.1 for loop
When using a for loop statement, you need to specify a variable and a list of possible values, and execute the same sequence of commands repeatedly for each different value until the variable value runs out and completely exit the loop. Here, the value list is the execution condition of the for statement, which includes multiple objects with the same attributes, which need to be specified in advance.
2.1.1 for loop format
for 变量名 in 取值列表
do
命令序列
done
Example: Add user and delete user
#!/bin/bash添加用户
ULIST=$(cat /root/user.txt)
for UNAME in $ULIST
do
useradd $UNAME
echo "123456" | passwd --stdin $UNAME &> /dev/null //把输出信息丢弃
done
#!/bin/bash删除用户
$ULIST=$(cat /root/user.txt)
for UNAME in $ULIST
do
userdel -r $UNAME
[$? -eq 0] && [echo "已删除用户$UNAME"]
done
2.1.2 Loop interrupt (break, continue)
By default, break jumps out of a single loop, break 2 jumps out of two loops, and so on, break n jumps out of n loops.
continue terminates a command in a loop, but does not completely terminate the entire loop
2.1.3 Three methods of for loop
方法1
[root@localhost ~]#for i in {1..10};do echo $i;done //按序输出1到10
[root@localhost ~]#for i in {1..10..2};do echo $i;done //输出1到10,步长为2
方法2
[root@localhost ~]#for i in $(seq 1 10);do echo $i;done //按序输出1到10
[root@localhost ~]#for i in $(seq 1 2 10);do echo $i;done //输出1到10,步长为2
方法3
[root@localhost ~]#for ((i=1;i<=10;i++));do echo $i;done
2.2 while loop
while 条件测试操作
do
命令序列
done
Example: Guess the commodity price
PRICE=$(expr $RANDOM % 1000)
TIMES=0
echo "good's price between 0-999,how much?"
while true
do
read -p "please input the price you guessed:" INT
let TIMES++
if [ $INT -eq $PRICE ];then
echo "You're right.The price is $PRICE"
echo "You have guessed $TIMES times."
exit 0
elif [ $INT -gt $PRICE ];then
echo "Too high!"
else echo "Too low!"
fi
done
2.3 until loop
Test a certain condition repeatedly, and execute it repeatedly as long as the condition is not established
until 条件测试操作
do
命令序列
done
Example: Accumulate from 1
#!/bin/bash
read -p "从1加到几?" num
i=0;s=0
until [ $i -eq $num ]
do
let "i++";let "s=$s+$i"
done
echo "sum(1...$num)="$s
Three functions
Function definition
[function] 函数名 ()
{
命令序列
[return x]
}
Call functions
函数名 [参数1] [参数2]
3.1 Function return value
Return means to exit the function and return an exit value. The script can use ? Variables to display the value. Principles of use: 1 Take the return value as soon as the function ends, because? Variables display the value. Principles: 1 Take the return value when the function ends ,because? Variable amount significantly shown the value makes use of the original is : a function number of a junction beam to take returns back to value , because as ? Variable returns only the last command executed exit status
2 exit status code must be 0-255, beyond When dividing by 256, take the remainder
db()
{
read -p "input:" value
return $[$value * 2]
}
db
echo $?
3.2 Recursive function
The recursive function calls itself. When analyzing the function, you can skip the function call and then analyze the part.
Example: Recursively traverse directories and executable files in environment variables
#!/bin/bash
//递归函数部分
file_list() {
for f in $1/* // $1/*表示取值列表,读取PATH下目录
do
if [ -d $f ];then //对$f进行判断,-d表示是否为目录
echo "$2$f"
file_list "$f" " $2" //调用函数自身,把$f下的所有目录和文件作为取值列表,再次进行判断
elif [ -x $f ];then //对$f进行判断,-x表示是否为可执行文件
echo "$2$f" //输出空格接该文件
fi
done
}
//主程序部分
IFS=$IFS':' //IFS字段分隔符,默认包含空格,换行,制表符,加入':'对冒号也可以识别并进行分隔
for folder in $PATH
do
echo "$folder:"
file_list "$folder" " " //调用函数,加入位参1,2
done
3.3 Creation and calling of function library
Example: Addition, subtraction, multiplication and division function library
创建函数库
[root@localhost ~]#vim myfuncs.sh
jiafa()
{
echo $[$1+$2]
}
jianfa()
{
echo $[$1-$2]
}
chengfa()
{
echo $[$1*$2]
}
chufa()
{
if [ $2 -ne 0 ];then
echo $[$1/$2]
else
echo '$2不能为0'
fi
}
//调用函数库
. myfuncs.sh
value1=10
value2=5
result1=`jiafa $value1 $value2`
result2=`jianfa $value1 $value2`
result3=`chengfa $value1 $value2`
result4=`chufa $value1 $value2`
echo "加法结果为$result1"
echo "减法结果为$result2"
echo "乘法结果为$result3"
echo "除法结果为$result4"
Four for loop output ninety-nine multiplication table, diamond
4.1 Multiplication table
#!/bin/bash
for ((i=1;i<=9;i++)) //外循环控制行数
do
for ((j=1;j<=i;j++)) //内循环控制列数
do
echo -n -e "$i x $j = $((i * j))\t"
done
echo -e "\n"
done
4.2 Diamond
#!/bin/bash
#菱形上半部分
for ((i=9;i>=1;i--)) #控制行数
do
for ((a=1;a<=$i;a++)) #控制第i行第一段输出
do
echo -n " "
done
for ((b=9;b>=$i;b--)) #控制第i行第二段输出
do
echo -n "*"
done
for ((c=8;c>=$i;c--)) #控制第i行第三段输出
do
echo -n "*"
done
echo ""
done
#菱形下半部分
for ((h=2;h<=9;h++))
do
for ((d=1;d<=$h;d++))
do
echo -n " "
done
for ((e=9;e>=$h;e--))
do
echo -n "*"
done
for ((f=8;f>=$h;f--))
do
echo -n "*"
done
echo ""
done