Linux---shell編程總結之處理用戶輸入(四)

1、位置參數從$0~$9,$0是程序名字,$1是第一個參數以此類推
例子:

factorial=1
for (( number = 1; number <= $1; number++ ))
do
	factorial=$[ $factorial * $number ]
done
echo The factorial of $1 is $factorial.

例子2:

name=$(basename $0)
if [ $name = "addem" ]
then
	total=$[ $1 + $2 ]
elif [ $name = "multem" ]
then
	total=$[ $1 * $2 ]
fi
echo
echo The calculater value is $total

2、特殊變量$#含有腳本運行的命令行參數的個數,不是每個參數的值
例子:

if [ $# -ne 2 ]
then
	echo
	echo Usage: test9.sh a b
	echo
else
	total=$[ $1 + $2 ]
	echo
	echo The total is $total
	echo
fi

3、命令行參數的最後一個是什麼可以通過${!#}來顯示
例子:

params=$#
echo
echo The last parameter is $params
echo The last parameter is ${!#}
echo

4、訪問每個參數的值可以用$*和$@變量,$*是將命令行參數作爲一個整體,而$@會單獨處理每一個命令行參數
例子:

for param in "$*"
do
	echo "\$* Parameter #$count = $param"
	count=$[ $count + 1 ]
done

echo
count=1
for param in "$@"
do
	echo "\$@ Parameter #$count = $param"
	count=$[ $count + 1 ]
done

代碼結果爲:
$* Parameter #1 = 1 2 3

$@ Parameter #1 = 1
$@ Parameter #2 = 2
$@ Parameter #3 = 3   (區別就在這裏)

5、移動變量:移動變量使用的是shift命令,可以將$2命令行參數移至$1,而之前$1裏面的值將會被刪除
例子:

echo
count=1
while [ -n "$1" ]
do
        echo "Parameter #$count = $1"
        count=$[ count + 1 ]
        shift
done

一次性移動幾個位置:在shift後面寫上數字
例子:

echo
echo "The original parameters: $*"
shift 2 
echo "Here's the new first parameter: $1"

6、獲得用戶的輸入:使用read命令來獲取用戶的輸入,-p選項順便帶了打印功能,減少了echo的數量

echo -n "Enter your name: "
read name
echo "Hello $name, welcome to muy program."
----------------------------------------------------------------
read -p "Please enter you age: " age
days=$[ $age * 365 ]
echo "That makes you over $days days old!"

如果read命令中不指定變量,那麼默認存在環境變量REPLY中
例子:

read -p "Enter you name: "
echo
echo Hello $REPLY, welcome to my program.

-t選項則指定了超時時間,超過了定義時間不輸入就會自動結束read輸入
-s選項可以在隱藏你在read上的輸入,就像登陸系統看不見密碼一樣
-n選項指定了輸入的字符數

7、通過read line來讀取文件中的數據:read line則可以讀取文件中的每一行
例子:

count=1
cat test | while read line
do
	echo "Line $count: $line"
	count=$[ count + 1 ]
done
echo "Finished processing the file"
發佈了8 篇原創文章 · 獲贊 1 · 訪問量 290
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章