bash-高級編程--位置變量

特殊變量類型

局部變量

這種變量只有代碼塊或者函數中才可見

如果變量用local 來聲明, 那麼它就只能夠在該變量被聲明的代碼塊中可見. 這個代碼塊就是局
部"範圍". 在一個函數中, 一個局部變量只有在函數代碼塊中才有意義.

環境變量

這種變量將影響用戶接口和shell的行爲

通常情況下,每個進程都有自己的"環境",這個環境是由一組變量組成的, 這些變量存有進程可能需要引用的信息。

一個腳本可以通過export傳遞環境變量給子進程,但是子進程不能傳遞環境變量給父進程。

位置參數

從命令行傳遞到腳本的參數:$0, $1, $2, $3 ...

$0就是腳本自身的名字

#! /bin/bash
# 這個腳本用於測試腳本變量
# $0 代表變量本省
echo -e '$0' "= $0"
# 腳本的第一個參數
echo -e '$1' "= $1"
# 第二個參數
echo -e '$2' "= $2"
# 第三個參數
echo -e '$3' "= $3"

運行結果:

andrew@andrew:/work/linux-sys/bash/2.基本/src$ bash bash_name.sh  name s d
$0 = bash_name.sh
$1 = name
$2 = s
$3 = d

bash_name_test.sh

#!/bin/bash
# 作爲用例, 調用這個腳本至少需要10個參數, 比如:
# bash bash_name_test.sh 1 2 3 4 5 6 7 8 9 10
MINPARAMS=10

echo

echo "The name of this script is \"$0\"."
# 添加./是表示當前目錄
echo "The name of this script is \"`basename $0`\"."
# 去掉路徑名, 剩下文件名, (參見'basename')

echo

if [ -n "$1" ]
# 測試變量被引用.
then
  echo "Parameter #1 is $1" # 需要引用才能夠轉義"#"
fi

if [ -n "$2" ]
then
  echo "Parameter #2 is $2"
fi

if [ -n "$3" ]
then
   echo "Parameter #3 is $3"
fi
 
# ...


if [ -n "${10}" ] # 大於$9的參數必須用{}括起來.
then
  echo "Parameter #10 is ${10}"
fi
 
echo "-----------------------------------"
echo "All the command-line parameters are: "$*""

if [ $# -lt "$MINPARAMS" ]
then
  echo
  echo "This script needs at least $MINPARAMS command-line arguments!"
fi

echo

exit 0

執行結果

andrew@andrew:/work/linux-sys/bash/2.基本/src$ bash ./bash_name_test.sh   1 2 3 4 5 6 7 8 9 0 

The name of this script is "./bash_name_test.sh".
The name of this script is "bash_name_test.sh".

Parameter #1 is 1
Parameter #2 is 2
Parameter #3 is 3
Parameter #10 is 0
-----------------------------------
All the command-line parameters are: 1 2 3 4 5 6 7 8 9 0

有時候腳本中需要在不知道輸入 多少參數的情況下,定位到最後一個可以 藉助$#實現, $#表示參數的個數的變量

args=$#
# 位置參數的個數.
lastarg=${!args}
# 或:
lastarg=${!#}
#(感謝, Chris Monson.)
# 注意, 不能直接使用 lastarg=${!$#} , 這會產生錯誤.
shift命令會重新分配位置參數,其實就是把所有的位置參數向左移動一個位置

使用shift將位置參數進行整體的左移

#! /bin/bash
# shift 是將位置參數整體向左移動的命令

# $@是,一個一個打印出命令參數
# $* 與$@達到的效果一樣,但是$*是講位置參數作爲一個整體輸出的意思

echo "$@"

shift

echo "$@"

shift 

echo "$*"
andrew@andrew:/work/linux-sys/bash/2.基本/src$ bash shift_test.sh 1 2 3 5 6 
1 2 3 5 6
2 3 5 6
3 5 6
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章