【Shell】Shell基础-语法

条件测试

测试命令:0为正确,非0为错误

test
[

数字之间的比较

-eq   #equal
-ne   #not equal
-lt   #小于 not less
-gt   #大于 great than
-le   #小于等于
-ge   #大于等于

eg1:

read myint   #从标准输入中输入数字
test $myint -eq 100  #检测myint与100是否相等
echo $?   #读取退出码

eg2:

[ $myint -lt 50 ]    #空格不能省略,这是命令行参数

字符串之间的比较

read mystring

eg1:

[ $mystring == "hello" ]   #空格不能省,省了就是字符串拼接了

eg2:

[ -z $mystring ]  #判断字符串是否为空

eg3:

[ -n $mystring ]  #判断是否为非空
echo $?

执行程序

sh shell.sh
#啥也不输入、回车

程序出错,说语法错误

执行改

sh -X shell.sh   #-X 测试模式

程序中修改

read mystring
[ "X"$mystring == "Xhello" ] # 避免语法错误

文件比较

-f    #-f 判断文件类型是否为普通文件
-d   #-d 判断文件类型是否为目录
-c   #-c 某个文件是否为字符设备文件(比如:键盘)
-b   #-b 是否为块设备文件(比如:磁盘(具有随机访问的能力))

eg:

[  -f ./shell.sh ]
echo$?

[ -d ./test ]

[ -c /dev/vsca1]

多条件判断:与 或 非

read mystring
[ "X"$mystring == "Xhehe" ]    #与
[ ! "X"$mystring == "Xhehe" ]
[ "X"$mystring != "Xhehe" ]  #非
  • 与 -a
read myint
[ $myint -lt 100 -a $myint -gt 50 ]
  • 或 -o
[ $myint -lt 50 -o $myint -gt 100 ]
  • if else
myint
if [ $myint -eq 100 ]; then
echo "hehe"
else
    echo "haha"
fi
  • elseif
if [ $myint -lt 100 ]; then
    echo "less than 100"
elif [ $myint -lt 150 -a $myint -gt 100 ]; then
    echo "greater equal 100 and lt 150"
else
    echo "gt 150"
fi
read myint
if [ $myint -lt 100 ]; then
:    #空语句,不能省
else
    echo "hehe"
fi
  • &&:表示 if then
read myint
[ $myint -eq 100 ] && echo "hehe"
  • ||:表示 if not then
执行:
make clean && make -j16 && make
#make  只用单线程编译
#-j16 用16个进程编译,多线程编译,效率更高
  • case
read mystring
case $mystring in
    'start' )
    #或:'start' | -s # -s等价于start
    # 或:'[Ss]tart' | -s ) 
        echo "start..."
    'stop' )
        echo "stop..."
        ;;
    * )
        echo "default..."
        ;;
esac
  • 循环for
for (( i=0;i<10;++i ))
do 
    echo $i
done
  • for in
for i in {0..9}
do 
    echo $i
done
for i in {0..9} {a..z}
do
    echo $i
done
  • while
i=0
while [ $i -lt 5 ]
do
    echo $i
    (( ++i )) 或 let ++i
done
  • until:条件为假就继续循环,条件为真,跳出循环
    来写个死循环
for (( ; ; ))
do
    echo "hehe"
    sleep 1
done
while :
do
    echo "hehe"
    sleep 1
done
while ture
do
    echo "hehe"
    sleep 1
done
until false
do
    echo "hehe"
    sleep 1
done

来个练习

* 1. 求1加到100,打印结果和算式*

i=0
sum=0
str=''
for(( i=1;i<=100'++i ))
do
    (( sum=$sum+$i ))
    if [ -z $str ]; then
        str=$i
    else
        str=$str'+'$i
    fi
done
    echo &sum"="$str

* 2.求1加到100所有奇数和并打印 *

与上面代码一样
将 ++i 改为 i += 2

特殊变量

$0,$1,$2...   命令行参数
echo "\$0 => $0"
echo "\$1 => $1"

执行输入:sh shell.sh aa
结果:

# $# 相当于argc-1
# $@ 相当于第二个参数  aa
# $? 上个进程的退出码

猜你喜欢

转载自blog.csdn.net/weixin_38682277/article/details/80579934
今日推荐