Linux学习命令之Shell编程入门

       Shell脚本是批处理执行命令,其后缀为.sh。一般在执行其之前需要先执行如下chmod命令以给脚本filename 增加可读可写可执行的权限。

chmod 777 filename.sh

1、字符串输出(echo)

#! /bin/bash
echo "hello world"

使用echo命令将字符串 hello world 输出到终端上。

2、定义变量

#! /bin/bash
num=1
echo $num

给变量num赋值1并输出其值至终端上。(注意:变量与“=”之间不能有空格)

3、读取键盘输入的字符变量(read) 

#! /bin/bash
echo "please input your ID:"
read ID
echo "your ID is $ID"

使用read命令读取键盘上输入的ID字符串并将其输出到终端上。

4、四则运算(expr)

#! /bin/bash
num1=100
num2=200
result1=`expr $num1 + $num2`  #加法
result2=`expr $num2 - $num1`  #减法
result3=`expr $num2 \* $num1` #乘法(注意:*前必须带符号\)
result4=`expr $num2 / $num1`  #除法
echo "$result1 $result2 $result3 $result4"

使用expr命令进行四则运算并将结果输出到终端上。(注意: ` 字符为键盘上数字1前面的那个字符)

算术运算符:+、-、*、/、%、=、==、!=。

5、条件判断(if、case)

#! /bin/bash
echo "please input num1:"
read num1
echo "please input num2:"
read num2
if [ $num1 -lt $num2 ]
then 
echo "num1 is lower than num2"
elif [ $num1 -eq $num2 ]
then 
echo "num1 is equal with num2"
else
echo "num1 is greater than num2"
fi

使用 if 命令比较输入的两个数字的大小并将比较结果输出到终端上

#! /bin/bash
echo "please input num:"
read num
case $num in
1) echo "hello world!"
;;
3) echo "hello npc"
;;
*) echo "error: wrong number"
esac

  使用case命令匹配选项并执行相应的命令。

关系运算符:

-eq   检测两个数是否相等,相等返回true。

-ne   检测两个数是否不相等,不相等返回true。

-gt    检测左边的数是否大于右边的数,如果是返回true。

-lt     检测左边的数是否小于右边的数,如果是返回true。

-ge   检测左边的数是否大于等于右边的数,如果是返回true。

-le    检测左边的数是否小于等于右边的数,如果是返回true。

布尔运算符

!(非)、-a(与)、-o(或) 

6、循环语句(while、for、until)

#! /bin/bash
echo "please input num:"
read num
num1=`expr $num + 3`
while [ $num -lt $num1 ]
do 
  echo "$num"
  num=`expr $num + 1`
done

利用 while 语句从输入的数字开始连续输出三个自然数到终端上。

#! /bin/bash
for num in 0 1 2 3 4
do  
  echo "$num"
done

利用 for 语句连续输出0、1、2、3、4到终端上。

#! /bin/bash
num=2
until [ $num -lt 5 ]
do 
  echo "$num"
  num=`expr $num + 1`
done

利用 until 语句连续输出2、3、4到终端上。

7、shell中自定义函数的使用

#! /bin/bash
fun_1()
{
   echo "$1"
   echo "$2"
   echo "$3"
   echo "func load args $*"
   echo "func args $#"
   return $(($1 + $2 + $3))
}
fun_1() 2 3 4
sum=$?
echo $sum

$#    传递给函数的参数的个数。

$*     显示所有传递给函数的参数。

$@   与$*相同,但有所区别。

$?     函数的返回值。

8、shell 中的数组

#! /bin/bash
array=(1 2 3 4)
count=0
array_length=${#array[@]}
while [ $count -lt $array_length ]
do 
  echo "array[$count] = ${array[$count]}"
  count=`expr $count + 1`
done

创建数组并将其输出到终端上。

shell数组的特性和C差不多,下标也是从0开始计算的。

猜你喜欢

转载自blog.csdn.net/weixin_44928892/article/details/102874331