脚本最好都放在/usr/local/sbin中
脚本的执行 sh -x 脚本.sh -x可以查看执行过程
1在脚本中使用变量 使用变量的时候,需要使用$符号:
#!/bin/bash
##把命令赋值为变量,需要使用反引号
d=`date +"%H:%M:%S"`
echo "The script begin at $d"
echo "Now we'll sleep 2 seconds"
sleep 2
d1=`date +"%H:%M:%S"`
echo "The script end at $d"
2在脚本中使用数学运算要用[]括起来如下
#! /bin/bash
a=1
b=2
##数学运算用[]括起来
sum=$[$a+$b]
echo "$a + $b = $sum"
3在脚本中和控制台交互 使用read命令
#! /bin/bash
read -p "Please input a number: " x
read -p "Please input a number: " y
sum=$[$x+$y]
echo "The sum of the tow numbers is : $sum"
4shell中的预设变量
#! /bin/bash
echo "$1 $2 $3 $0"
1 2 就是脚本中的预设变量 一个脚本中的预设变量是没有限制的,0表示脚本文件本书
# sh option.sh 1 2 3
执行此命令输出内容如下所示:
1 2 3 option.sh
5shell中的逻辑判断
不带else的if 注意if后面的判断语句要用(())否则会报错
#! /bin/bash
read -p "Please input your score: " a
if ((a<60)); then
echo "You didn't pass the exam."
fi
5.1带else 实例代码如下
#! /bin/bash
read -p "Please input your score: " a
if ((a<60)); then
echo "You didn't pass the exam."
else
echo "Good! You passed the exam."
fi
5.2带有else if(这是c中的说法)在shell中表示为elif
#! /bin/bash
read -p "Please input your score: " a
if ((a<60)); then
echo "You didn't pass the exam."
elif ((a>=60)) && ((a<85)); then
echo "Good! You passed the exam."
else
echo "Very good! Your score is very heigh"
fi
5.3case 逻辑判断
#! /bin/bash
read -p "Input a number: " n
a=$[$n%2]
case $a in
1)
echo "The number is odd."
;;
0)
echo "The number is even."
;;
*)
echo "It's not a number"
;;
esac
* 表示其他值
6for循环
实例代码如下:
#! /bin/bash
for file in `ls`;do
echo $file
done
7while 循环
#! /bin/bash
a=5
while [ $a -ge 1 ]; do
echo $a
a=$[$a-1]
done