五.Shell之3種內部變數高階用法(DIRSTACK、GLOBINGURE、SECONDS)
1. DIRSTACK(目錄棧)
它顯示目錄棧的棧頂值
,和我們常見的棧一樣為先進先出
,擁有入棧
和出棧
兩個動作。和DIRSTACK
相關的命令如下:
-
dirs (顯示目錄棧)
注意與dir不同
格式:
dirs [-clpv] [+N] [-N]
選項:
-c
刪除所有元素以清空目錄棧
-l
不列印與主目錄相關的波浪號字首的目錄
-p
每行一個條目列印目錄棧
-v
每行一個條目,以棧中位置為字首列印目錄棧
引數:
+N
顯示 dirs 不帶選項啟動時顯示的目錄列表左起中第N 個目錄,從零開始。
-N
顯示 dirs 不帶選項啟動時顯示的目錄列表右起中第N 個目錄,從零開始。
Demo:
$ popd bash: popd: 目錄棧為空 #表明現在目錄棧為空 $ echo $DIRSTACK /home/jin1ming $ pushd . ~ ~ $ pushd go ~/go ~ ~ $ pushd ../linux_shell ~/linux_shell ~/go ~ ~ $ dirs -l -p /home/jin1ming/linux_shell /home/jin1ming/go /home/jin1ming /home/jin1ming $ dirs -v 0~/linux_shell 1~/go 2~ 3~ $ dirs +1 ~/go $ dirs +2 ~ $ dirs -l -p /home/jin1ming/linux_shell /home/jin1ming/go /home/jin1ming /home/jin1ming $ dirs +0 ~/linux_shell $ dirs -1 ~ $ dirs -0 ~ $ dirs -2 ~/go
-
pushd (將目錄壓棧)
格式:
pushd [-n] [+N | -N | 目錄]
選項:
-n
抑制新增目錄至棧時通常的改變目錄操作,從而僅對棧進行操作。
引數:
+N
旋轉棧從而第 N 個目錄 (`dirs' 顯示的列表中左起,從零開始)將移動到棧頂。
-N
旋轉棧從而第 N 個目錄 (`dirs' 顯示的列表中右起,從零開始)將移動到棧頂。
dir
將 DIR 目錄新增到棧頂,並且使其成為當前工作目錄。
通俗來講:+N、-N就是將第N個目錄移到棧頂,相當於一個迴圈連結串列的指標往後(+N)移了2次。
Demo:
$ pushd -n go ~ go $ pushd -n linux_shell ~ linux_shell go $ pushd -n /hoem ~ /hoem linux_shell go $ pushd -n /home ~ /home /hoem linux_shell go $ dirs -v -l 0/home/jin1ming 1/home 2/hoem 3linux_shell 4go
/hoem
為我不小心打錯,但由此可見,絕對目錄
即便是不存在的也可以成功壓棧。
- popd (將目錄彈出棧)
選項:
-n
抑制從棧中刪除目錄時通常的目錄變換操作,從而僅對棧
進行操作。
引數:
+N
刪除第 N 個目錄 (`dirs' 顯示的目錄列表中左起,從零開始)。
例如:`popd +0' 刪除第一個目錄,`popd +1' 刪除第二個。
-N
刪除第 N 個目錄 (`dirs' 顯示的目錄列表中右起,從零開始)。
例如:`popd -0' 刪除最後一個目錄,,`popd -1' 刪除倒數第二個。
2. GLOBIGNORE (通配時忽略)
GLOBIGNORE
是由冒號
分隔的模式列表,表示通配時忽略的檔名集合
。
Demo:
$ cd linux_shell/ $ ls 1.txt4aa4ae4aiawkdomo2.awknew1.txtselectdomo.shtestgo.sh 24ab4af4ajawkdomo.awkphoneinfoshelldemo.shtest.sh 2.txt4ac4ag4akfilescoresort1.txt 34ad4ah4alfordemo.shselectdemo.shsort2.txt $ GLOBIGNORE="*.sh:*.awk" $ ls * 1.txt2.txt4aa4ac4ae4ag4ai4akfilephoneinfosort1.txt 234ab4ad4af4ah4aj4alnew1.txtscoresort2.txt $ ls 1.txt4aa4ae4aiawkdomo2.awknew1.txtselectdomo.shtestgo.sh 24ab4af4ajawkdomo.awkphoneinfoshelldemo.shtest.sh 2.txt4ac4ag4akfilescoresort1.txt 34ad4ah4alfordemo.shselectdemo.shsort2.txt
3.SECONDS (記錄指令碼執行時間)
SECONDS
記錄指令碼
從開始到結束所耗費的時間
,以秒
為單位。也可以記錄終端
開啟的時間。
Demo:
$ echo $SECONDS 21 $ echo $SECONDS 25 $ echo $SECONDS 27 $ echo $SECONDS 37 $ SECONDS=0;echo $SECONDS 0 $ cat secondsdemo.sh #!/bin/bash sum=0 for num in {1..10} do let "sum+=num" sleep 1 done echo "sum=$sum" echo "Running time is $SECONDS." $ ./secondsdemo.sh sum=55 Running time is 10.