shell脚本常用

一.内部常用命令

  1. echo 在屏幕上输出
    -n 不会换行
    -e 会识别换行符\n
  2. printf 产生各种格式的输出
  3. export 定义全局变量 export 变量名=变量值
  4. read 读入数据
    read -p “我是提示语句” file
    -t 指定等待时间
    -n指定字符串长度
    -s 隐藏输入的数据
    -p:输入提示符
  5. exec
    如:exec echo $a
    shell里,作为独立进程去执行该命令
  6. expr
    expr length “this is a test”
    expr substr “this is a test” 3 5
    expr index “sarasara” a
    expr 10 + 10 //+、-、、/、%
    expr 30 \
    3 //乘用 反斜杠*表示

二、控制、循环语句

1. if语句

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
cd ..
if [ -f test1.txt ]
then
echo test.txt is a fail;
cat test1.txt
elif [ -d shell ]
then
echo in shell is dir;
dir shell #打印出shell目录中的内容
fi

注意:

数值判断:
-eq 等于
-ge 大于等于
-gt 大于
-le 小于等于
-lt 小于
-ne 不等于
字符串判断(两边有个空格)
= 等于
!= 不等于
-z 字符串长度为零
-n 字符串长度不为零
文件测试
-d 如果文件存在且为目录,则为真
-e 如果文件存在
-f 如果文件存在且为普通文件
-r ….且可读
-w ….且可写
-x ….且可执行
-s ….且至少有一个字符

2.switch语句

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
cd ..
echo "please choice to display is file";
echo "1:display test.txt";
echo "2:display test1.txt";
echo enter your choice;
read -p "please in num:" var
case $var in
1) cat test.txt;;
2) cat test1.txt;;
*) echo error;;
esac

3.for语句

1
2
3
4
5
6
#!/bin/bash
for num in 1 2 3 4 5 6 7 8 9 10
do
echo $num is:
expr $num \* $num
done

4.while语句

1
2
3
4
5
6
7
8
9
#!/bin/bash
echo "please input number(gt 100 will quit)";
read num;
while [ $num -lt 100 ]
do
echo result:
expr $num \* $num;
read num;
done

5. until语句

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
echo "please input fileName:"
read filename;
echo "please input fileContent(in 'end! quit!!!'):"
read fileContent;
until [ $fileContent = "end!" ]
do
$fileContent >> $filename #写内容到这个文件去
echo "please input fileContent(in 'end! quit!!!'):" read fileContent
done

三、其他常用

  1. 引号含义:
    反引号:shell中 会首先执行反引号的代码
    单引号:不是解释,原封不动打印出来
    双引号:解释变量,而且保留空格
    没有引号:解释变量,不会保留空格
  2. $符号含义
    $#表示用户输入参数的个数
    $0 是脚本本身的名字
    $? 是显示最后命令的退出状态,0表示没有错误,其他表示有错误
    $$ 是脚本运行的当前进程ID号
    $@
    $*
    $! 后台运行程序的pid
    都是代表说有, $@每一个会被区别对待
    num# 8# 16# 2# 代表进制
  3. 运算
    sum=$(($sum$i)) 等于 let “sum=sumi” == s
    $i == ${i}
  4. 小括号,中括号,双括号,大括号区别
    if ($i<5)

    1
    2
    3
    4
    5
    6
    7
    8
    if [ $i -lt 5 ]    
    if [ $a -ne 1 -a $a != 2 ]
    if [ $a -ne 1] && [ $a != 2 ]
    if [[ $a != 1 && $a != 2 ]]
    for i in $(seq 0 4);do echo $i;done
    for i in `seq 0 4`;do echo $i;done
    for ((i=0;i<5;i++));do echo $i;done
    for i in {0..4};do echo $i;done
  5. 注意
    shell脚本对空格有严格的规定,赋值语句等号两边不能有空格,而字符串比较,等号两边必须有空格

lightquant wechat
欢迎您订阅灯塔量化公众号!