歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux Shell腳本編程入門

Linux Shell腳本編程入門

日期:2017/3/1 9:26:20   编辑: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表示支持轉義字符

運行效果:

Linux Shell在while中用read從鍵盤輸入 http://www.linuxidc.com/Linux/2015-06/118831.htm

Linux Shell 程序調試 http://www.linuxidc.com/Linux/2015-07/119880.htm

Linux Shell腳本面試25問 http://www.linuxidc.com/Linux/2015-04/116474.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、轉義字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved