1. 程式人生 > >Linux學習之Shell 基礎——Bash變數——位置引數 變數

Linux學習之Shell 基礎——Bash變數——位置引數 變數

1、位置引數變數

位置引數變數 作用
$n n為數字,$0代表命令本身,$1-$9代表第一到第九個引數,十以上的引數需要用大括號包含,如${10}
$* 這個變數代表命令列中所有的引數,$*把所有的引數看成一個整體
[email protected] 這個變數也代表命令列中所有的引數,不過[email protected]把每個引數區分對待
$# 這個變數代表命令列中所有引數的個數

》$n 一般用於獲取比如使用者輸入的內容,通過該變數向系統傳遞使用者所輸入的內容。

[[email protected] ~]#cd sh
[[email protected] sh]#vim canshu1.sh

#!/bin/bash

echo $0
echo $1
echo $2
echo $3
~                                                                                       
~             
[[email protected] sh]#
[[email protected] sh]#chmod 755 canshu1.sh 
[
[email protected]
sh]#./canshu1.sh ./canshu1.sh [[email protected] sh]#./canshu1.sh 11 22 33 44 55 ./canshu1.sh 11 22 33 [[email protected] sh]#

示例2:簡單的加法計算器(當前有很多漏洞)

[[email protected] sh]#vim jiafajisuanqi.sh 

#!/bin/bash

num1=$1
num2=$2
sum=$(($num1 + $num2))
#變數sum的和是num1+num2
echo $sum
#列印變數sum的值
~                                                                                       
~       
[
[email protected]
sh]#chmod 755 jiafajisuanqi.sh [[email protected] sh]#./jiafajisuanqi.sh 2 3 5

》示例三

[[email protected] sh]#vim shili3.sh 

#!/bin/bash

echo "A total of $# parameters"
#使用$#代表所有引數的個數

echo "The parameters is:$*"
#使用$*代表所有的引數

echo "The parameters is:[email protected]"
#使用[email protected]也代表所有引數

[[email protected] sh]#chmod 755 shili3.sh 
[[email protected] sh]#./shili3.sh 
A total of 
The parameters is:
The parameters is:
[[email protected] sh]#./
canshu1.sh        hello.sh          jiafajisuanqi.sh  shili3.sh
[[email protected] sh]#./shili3.sh 4 55 44 3 2 5
A total of 6 parameters
The parameters is:4 55 44 3 2 5
The parameters is:4 55 44 3 2 5
[[email protected] sh]#

示例4、$*與[email protected]的區別

[[email protected] sh]#vim canshu4.sh 

#!/bin/bash

for i in "$*"
#$* 中所有引數看成是一個整體,所以這個for迴圈只會迴圈一次
do
   echo "The parameters is:$i"

done
x=1

for y in "[email protected]"
#[email protected]中的每個引數都看成是獨立的,所以“[email protected]"中,有幾個引數就會迴圈幾次

do
  echo "The parameter $x is:$y"
  x=$(( $x + 1 ))
done

~                           
[[email protected] sh]#
[[email protected] sh]#chmod 755 canshu4.sh 
[[email protected] sh]#./canshu
canshu1.sh  canshu4.sh  
[[email protected] sh]#./canshu4
bash: ./canshu4: 沒有那個檔案或目錄
[[email protected] sh]#./canshu4.sh 3 4 3 2
The parameters is:3 4 3 2
The parameter 1 is:3
The parameter 2 is:4
The parameter 3 is:3
The parameter 4 is:2
[[email protected] sh]#