Linux Shell脚本编程入门

最近在学shell,记录一下。

if语句的使用:


1.判断两个参数大小


#!/bin/sh
#a test about if statement
a=10
b=20
if [ $a -eq $b ];then
echo "parameter a is equal to parameter b"
elif [ $a -le $b ];then
echo "parameter a is less than parameter b"
elif [ $a -gt $b ];then
echo "parameter a is greater than parameter b"
else
echo "i don't know the result!"
fi

2.执行脚本时动态传递参数

$1、$2、$3...分别代表接收到的参数
$0 表示程序的名称
$#  传递给程序的总的参数数目  
$? 上一个代码或者shell程序在shell中退出的情况,如果正常退出则返回0,反之为非0值
$*  传递给程序的所有参数组成的字符串
$@ 以"参数1" "参数2" ... 形式保存所有参数   
$$ 本程序的(进程ID号)PID   
$!  上一个命令的PID

脚本

#!/bin/sh
#a test about if statement
a=$1
b=$2
if [ $a -eq $b ];then
echo "parameter a is equal to parameter b"
elif [ $a -le $b ];then
echo "parameter a is less than parameter b"
elif [ $a -gt $b ];then
echo "parameter a is greater than parameter b"
else
echo "i don't know the result!"
fi

执行效果:
这里写图片描述


3.for循环的使用


#!/bin/bash
#a test about for and while statement
for i in {1..5}
do
 echo "hello world"$i
done

注意:这里sh不支持这种写法,要用bash来运行

sh支持这种写法:

#!/bin/sh
#a test about for and while statement
for i in 1 2 3 4 5
do
 echo "hello world"$i
done

4.在/root/test/test2文件夹中创建100文件夹,名称为test1~test100


#!/bin/bash
#create 100 folder in /root/test/test2
for i in {1..100}
do
`mkdir ./test2/test$i`
done

这里写图片描述


5.编写乘法表,根据输入参数来输出某个数的乘法表


#!/bin/bash
for((i=1;i<=$1;i++)){
    for((j=1;j<=${i};j++)){
       ((ret=${i}*${j}))
       echo -ne ${i}*${j}=$ret"\t" 
    }
    echo
}

注意:参数中的-n表示输出后不换行,e表示支持转义字符

运行效果:
这里写图片描述

猜你喜欢

转载自www.linuxidc.com/Linux/2015-08/121394.htm