shell 基本语法 (上)
本文目录
echo $PATH
一、变量
1、环境变量
echo $PATH
2、自定义变量
hello="hello_world" echo $hello
3、存储linux命令执行结果作为变量
(2种方式,推荐使用第二中,第一种是 ~键上面的斜点比较难识别)
files=ls -al
path=$(pwd)
注意点
定义变量=号两边不能有空格
使用变量需要加 $ 符号
二、基本预算
1、运算符
+:加 -:减 *:乘 /:除 %:取余 ==:判断是否相等 !=:不等于
:大于 =:大于或等于 <:小于 <=:小于或等于
2、整数运算(expr)
expr 10 + 3
echo $[10 + 3]
将计算结果存储为变量2种方式
num=$(expr 10 + 3)
num=`expr 10 + 3`注意点 运算符前后必须用空格 *乘必须加反斜杠转义
3、整数运算($[])
num1=100
num2=200
sum_num=$[$num1+num2]注意点 运算符前后可以不空格 *乘不需要加转义符
4、浮点运算
num=$(echo "scale=2;10/3" | bc)scale:保留小数的位数 将10/3给bc计算器计算,保留两位小数
三、条件选择
if后面接的是命令,其实是这个命令的退出状态码,正常退出,状态码0,其他的就不是0 这里意思是如果是0就执行then,否则就不执行 1、
if-then
if command
then
"执行成功"
fi2、
if-then-else3、
if-then-elif-else
if判断基本语法,if开头,fi结尾#/bin/bash
NUM='4'
if (( $NUM > 4 ))
then
echo "$NUM more then 4"
elif (( $NUM == 4 ))
then
echo "$NUM 等于4"
else
echo "$NUM less then 4"
ficase语句
case $num in
1)
echo "num=1"
2)
echo "num=2"
3)
echo "num=3"
esac四、循环
for - in
for i in list
do
commands
doneC语言风格
for (( i = 0;i <= 10;i++))
do
commands
donewhile循环
while test command
do
echo "条件满足的时候执行这里的操作"
donenum=8
while (( $num < 10 ))
do
echo "条件满足的时候执行这里的操作"
echo "$num小于10"
doneuntil循环
until test command
do
echo “条件不满足的时候执行”
done说明:
condition为条件表达式,值为false,则继续执行循环体内语句,否则跳出循环
until循环与while循环处理方式刚好相反
控制循环 break 跳出外层循环,同python continue 终止当前循环,进入下一个循环,同python
while (( 1>0 ))
do
echo –n “输入一个数字”
read num
if (( $num>10 ))
then
break
else
continue
fi
done五、命令行参数处理
bash shell 可以根据参数位置来获取参数 通过$1到$9获取第1到第9个命令行参数 $0为shell名,如果参数超过9个,就通过${10}来获取
六、获取用户输入(read)
单个输入,指定变量接收输入的值(choice)
echo -n "yes or no(y/n)"
read choice
echo "you choice is : $choice"单个输入,不指定变量接收输入的值,read会将它接收到的任何数据放到特殊环境变量REPLY中
echo -n "yes or no(y/n)"
read
echo "you choice is : $REPLY"多个输入
read -p "what is you name?" first second
echo first:$first
echo second:$second上面的例子首先会输出what is you name? 然后在本行等待用户输入 此处的read -p 实现以上实例的echo -n + read 不换行的效果 输入的参数用空格隔开 如果输入的值超出接收的变量个数,shell会把剩下的值都赋值给最后一个变量
七、超时设置
if read -t 5 -p "enter you name:"
name
then
echo "hello $name"
else
echo "time out"
fi注意点
变量名一般大写
数值比较 (( 8 > 7 ))
字符串比较 【【 str1 != str2 】】
test命令只能判断以下3类条件 数值比较 字符串比较 文件比较
shell脚本的流控制语句结束语句就是开始语句反过来写,如if 结束语句 fi,case结束语句esac
来源:testingpai