本帖参考https://blog.csdn.net/xmyzlz/article/details/8593228
1.脚本编写初步介绍
(1)脚本第一行以 #!/bin/sh 开始,也可以用 #!/bin/bash 开始,但是第一行必须以这种方式开始.
(2)脚本名需要以.sh结尾
(3)#开头的句子表示注释
(4)若要执行脚本文件,需给脚本赋权限,chmod 755 filenme
(5)脚本执行./filename
2.脚本变量
(1)所有的变量都由字符串组成,并且不需要对变量进行声明
#!/bin/sh
#对变量赋值:
a="hello world"
# 现在打印变量a的内容:
echo "A is:"
echo $a
执行结果为:
A is :
hello world
(2)有时候变量名很容易与其他文字混淆,如
num=2
echo "this is the $numnd"
执行结果:this is the ,脚本查找的变量是numnd,因此可以使用花括号来显示打印的是num变量
num=2
echo "this is the ${num}nd"
执行结果:this is the 2nd
(3)变量赋值时不要出现空格
3.脚本编辑
(1)if与[]之间有一个空格,[]里面前后需要一个空格,字符串进行比较只需要一个等号,=两边需要有一个空格,数字进行比较需要两个=,if条件还可以写为if (($n1>60))&&(($n1<90))
n1=2
n2=2
if [ $n1 == $n2 ]
then
echo "n1 is equal n2"
elif [ $n1 -gt $n2 ]
then
echo "n1 is greater than n2"
elif [ $n1 -lt $n2 ]
then
echo "n1 is less than n2"
else
echo "None of the conditoon met"
fi
(2)for循环
for((i=0;i<3;i++));
do
echo "this is "$i
done
结果为:
this is 0
this is 1
this is 2