Linux中shell脚本语句
1、语句规范
(1)Shell脚本通常都是以.sh 为后缀名的,一个习惯而已。
(2).sh为后缀的文件那么它可能是一个shell脚本了。
(3)test.sh中第一行要以 “#! /bin/bash” 开头,意思是该文件使用的是bash语法。 (4)如果不设置该行,虽然你的shell脚本也可以执行,但是这不符合规范.
(5)# 表示注释,后面跟一些该脚本的相关注释内容以及作者和创建日期或者版本等等。
(6)随着工作时间的逐渐过渡,你写的shell脚本也会越来越多,很有可能忘记该脚本是用来干什么的 以及什么时候写的。
(7)写上注释(注释是#)是有必要的。另外系统管理员并非只有你一个,如果是其他管理员查看你的脚本,他看 不懂岂不是很郁闷。
如:先在linux中随意创建一个以.sh的文件
即test.sh进入里面第一行写
date在shell中就代表其他语言中的 查看当前时间
echo 相当于其他语言中的 打印函数 它讲实现打印hello world
test.sh
#! /bin/bash
date
echo "Hello world! "
脚本写好如何执行
-
可以 sh test.sh 即可以查看结果
-
我发觉source test.sh 也可以执行脚本
-
给它加一个执行的权限
2、shell脚本中的变量
定义变量的格式
变量名=变量的值
如:a=1
变量的引用
在脚本中加上$
如:
#! /bin/bash
a=1
echo “number is $a”
输出结果:
number is 1 相当于把a的值传到那个位置了
注意:用的双引号,不要用单引号
3、shell脚本的动态输入(就算将用户的输入作为变量值)
跟c语言中的scanf 或者Python中的input函数差不多,都是用户动态从键盘输入
格式
read -p 加上你想要写的东西
如:
test.sh
#! /bin/bash
read -p "input your mark: " 空格 x 注意在x前面加一个空格不然它识别不出来
echo “mark:$x”
简单运算要用[ ]并且在最前面加一个$
test.sh
#! /bin/bash
read -p “number is :” 空格 x 注意在x前面加一个空格不然它识别不出来
read -p “number is :” 空格 y 注意在y前面加一个空格不然它识别不出来
sum= [ [ [x+$y]
echo “sum is $sum”
预设变量
就是直接给数值
test.sh
#! /bin/bash
sum=$[$1+$2]
echo “sum=$sum”
注意:执行语句变成了
sh -x test.sh 1 2 记住预算变量 只有1 和2 还有一个0 但是有特殊作用 不行你用它数值试试 会 报错
结果显示:
+ sum=3
echo sum=3
sum=3
4、shell脚本中的逻辑判断
1)不带else
格式:
if 判断语句;
then
command (条件判断时 要输出的内容)
fi
如:
#! /bin/bash
read -p "Please input your score: " a
if ((a<60)); then
echo “You didn’t pass the exam.”
fi
#这句话的意思就是,你要是小于60就会打印You didn’t pass the exam. 注意一下条件它要再用一个括号括住
2)带有else
格式:
if 判断语句 ; then
command (条件判断时 要输出的内容)
else
command (条件判断时 要输出的内容)
fi
如:
test.sh
#! /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.”
f i
3)带有elif
格式:
if 判断语句一 ; then
command
elif 判断语句二; then
command
else
command
fi
如:
test.sh
#! /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 pass the exam.”
else
echo “very good! Your socre is very high!”
fi
#这种用法跟python语句有点像