標籤:abs bash-shell advanced
變數替換
$variable 是 ${variable}的簡寫
39 hello="A B C D"
40 echo $hello # A B C D
41 echo "$hello" # A B C D
引號保留變數裡面的空白
1 echo "$uninitialized" # (blank line)
2 let "uninitialized += 5" # Add 5 to it.
3 echo "$uninitialized"
未初始化的變數是null,但是在算數運算式中等於0
命令替換
17 a=`ls -l` # Assigns result of ‘ls -l‘ command to ‘a‘
18 echo $a
或
a=$(ls -l)
echo $a
字串+整數等於整數,字串相當於0
但是在除以一個null變數的時候,系統報錯。
變數類型
本地變數
在代碼塊可見
環境變數
影響shell和使用者介面的變數
位置參數
取最後的參數
1 args=$# # Number of args passed.
2 lastarg=${!args}
或
lastarg=${!#}
[...]和[[...]]
使用[[...]]比起[]可以阻止在指令碼中常見的邏輯錯誤
例如:&&, ||, <, and > 操作
在進行算數運算的時候,[[...]]會將八進位和十六進位進行自動計算而[]
則不可以
5 decimal=15
6 octal=017 # = 15 (decimal)
7 hex=0x0f # = 15 (decimal)
8
9 if [ "$decimal" -eq "$octal" ]
10 then
11 echo "$decimal equals $octal"
12 else
13 echo "$decimal is not equal to $octal" # 15 is not equal to 017
14 fi # Doesn‘t evaluate within [ single brackets ]!
17 if [[ "$decimal" -eq "$octal" ]]
18 then
19 echo "$decimal equals $octal" # 15 equals 017
20 else
21 echo "$decimal is not equal to $octal"
22 fi # Evaluates within [[ double brackets ]]!
((...))算數測試
如果運算式計算是0,則它的退出狀態代碼是1或false
如果運算式計算是非0,則它的退出狀態代碼是0或true
它的退出狀態和[...]相反
echo ${aa##*/} 擷取變數aa的檔案名稱 以/位分隔字元
${filename##*.} != "gz"
filename##*. 擷取filename的副檔名
Infinite Monkeys
AppMakr
字串操作
擷取字串長度
${#string}
expr length $string
expr "$string" : ‘.*‘
擷取從字串開頭匹配的字串的長度
expr match "$string" ‘$substring‘
expr "$string" : ‘$substring‘
$substring is a regular expression
擷取子串在字串中開始的位置
expr index $string $substring
取出子串
${string:position}
${string:position:length}
本文出自 “Linux is belong to you” 部落格,請務必保留此出處http://jwh5566.blog.51cto.com/7394620/1657454
Advanced Bash-Shell Guide(Version 10) 學習筆記二