前言
最近在復習shell腳本的相關知識,本文列舉了一些在shell腳本中用得到的一些基礎語法。
1:打印常見內(nèi)部變量和環(huán)境變量值
shell中常用變量介紹
$0 | 腳本名 |
$n | 第n個參數(shù),n=1,2,3... |
$* | 所有參數(shù)列表(視為一個整體,不包括腳本名) |
$@ | 所有參數(shù)列表(獨立字符串、不包括腳本名) |
$# | 參數(shù)個數(shù)(不包含腳本名) |
$$ | 當前進程PID |
$! | 后臺運行的最后一個進程PID |
$? | 執(zhí)行上一個指令的返回值,如果為0,證明上一個命令正確執(zhí)行 |
#1:打印一些變量
echo $#
echo $0
echo $1
echo $$
echo $?
echo $!
echo "hello world"
echo $HOME
echo $PWD
?2:$@和$*之間的區(qū)別
#2:比較$@和$*
echo $@
echo $*
for var in "$@"
do
echo $var
done
for val in "$*"
do
echo $val
done
可以看到$@和$*不加“”括起來是沒有區(qū)別的,當用“”括起來之后,$@會將參數(shù)獨立看待,而$*會將全部參數(shù)視為一個整體。
3:自定義變量,將命令執(zhí)行的結果返回給變量
在自定義一個變量的時候“=”兩端不要加空格,可以將shell指令的返回值傳給變量
#3:自定義變量,定義的時候不要加空格,將命令的結果返回給變量
A=100
echo "A = $A"
B=$(pwd)
echo $B
4:運算符,實現(xiàn)加減乘除簡單算數(shù)操作
將表達式用[]括起來后里面的語句和正常的加減乘除操作相同
#4:運算符,實現(xiàn)加減乘除操作
SARFF=$[1200+4]
echo $SARFF
echo $[$1*$2]
5:if條件判斷,字符串(=),數(shù)值比較(-lt -gt -le -ge -eq -ne),文件權限(-r -w -x ),文件、目錄是否存在,是否為一個普通文件( -f -d -e)
shell腳本目錄下的文件和目錄
注意if語句的中括號兩端要有空格 ,否則會報錯
#5:條件判斷
if [ "ok100" = "ok" ]
then
echo "equal"
fi
if [ 30 -gt 20 ]
then
echo "greater than"
fi
if [ -r $0 ]
then
echo "$0 can read"
fi
if [ -w $0 ]
then
echo "$0 can write"
fi
if [ -x $0 ]
then
echo "$0 can execute"
fi
if [ -e 1.txt ]
then
echo "1.txt exists"
fi
if [ -d dir ]
then
echo "dir exists"
fi
if [ -f 1.txt ]
then
echo "1.txt is a normal file"
fi
6:流程控制
實現(xiàn)C語言中的if else 語句
#6:流程控制
if [ $1 -gt 60 ]
then
echo "$1 greater than 60"
elif [ $1 -le 60 ]
then
echo "$1 little equal 60"
fi
7:循環(huán)語句(for和while)
for循環(huán)和while循環(huán)都是實現(xiàn)1加到100的和
#7:for循環(huán)
SUM=0
for((i=1;i<=100;i++))
do
SUM=$[$SUM+$i]
done
echo "SUM = $SUM"
#while循環(huán)
j=0
NUM=0
while [ $j -le 100 ]
do
NUM=$[$NUM+$j]
j=$[$j+1]
done
echo "NUM = $NUM"
?
8:從控制臺輸入數(shù)據(jù),C語言中scanf函數(shù)功能
使用read來實現(xiàn)輸入功能,-p后的內(nèi)容是提示信息,-t可以限制輸入?yún)?shù)的時間
#8:從控制臺獲取參數(shù),實現(xiàn)scanf作用
read -t 5 -p "input a num" NUM2
echo "you input NUM2 = $NUM2"
在限制時間5s中之內(nèi)輸入數(shù)據(jù)?
超過5s還未輸入數(shù)據(jù)
9:函數(shù)的簡單使用
#9:自定義函數(shù)
function getAdd(){
SUM=$[$n1+$n2]
echo "SUM = $SUM"
}
read -p "input first num" n1
read -p "input second num" n2
getAdd $n1 $n2
定義函數(shù)要用function關鍵字,函數(shù)功能是實現(xiàn)求兩數(shù)的和
10:邏輯與、或、非
//邏輯與
if [ 30 -gt 20 ] && [ 10 -eq 20 ]
then
echo "true"
else
echo "false"
fi
//邏輯或
if [ 30 -gt 20 ] || [ 10 -eq 20 ]
then
echo "true"
else
echo "false"
fi
//邏輯非
if ! [ -r temp.txt ]
then
echo "true"
else
echo "false"
fi
?文章來源:http://www.zghlxwxcb.cn/news/detail-451514.html
總結
本文只涉及了shell腳本的一小部分內(nèi)容,目的是為了能夠使用shell腳本實現(xiàn)一些簡單的功能。文章來源地址http://www.zghlxwxcb.cn/news/detail-451514.html
到了這里,關于Shell腳本常見用法列舉的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!