SHELL小结
1. for遍历数组
for i2c in "6" "7"
—— 用双引号、空格将数组成员分开,即可。
2. 将字符和数字进行运算
RiserNum=$(echo $Riser | tr -dc '0-9') GPUNum=$(echo $GPU | tr -dc '0-9') RiserGPUSlot=$(((RiserNum-1)*4+GPUNum))
—— RiserGPUSlot结果则为运算后的数字。
Btw: 其中$Riser和$GPU都是带数字的字符,如Riser1, GPU1。RiserNum和GPUNum即取出来的数字。)
Ref: https://stackoverflow.com/questions/11268437/how-to-convert-string-to-integer-in-unix
d1="11" d2="07" echo $(( d1 - d2 ))
使用$(( ))的方式即可将括号里面的字符与数字进行表达式运算,获得结果。
3. 字符串比较
Sourcesystem="ABC" if [ "$Sourcesystem" = "XYZ" ]; then echo "equal!" fi
Ref: https://stackoverflow.com/questions/10849297/compare-a-string-in-unix
4. String Contains
string='My long string' if [[ $string == *"My long"* ]]; then
string='My string'; if [[ $string =~ .*My.* ]]
Ref: https://stackoverflow.com/questions/229551/string-contains-in-bash
contains() { string="$1" substring="$2" if test "${string#*$substring}" != "$string" then return 0 # $substring is in $string else return 1 # $substring is not in $string fi } contains "abcd" "e" || echo "abcd does not contain e" contains "abcd" "ab" && echo "abcd contains ab"
Ref: https://stackoverflow.com/questions/2829613/how-do-you-tell-if-a-string-contains-another-string-in-unix-shell-scripting
5. 获得命令执行的结果
var=`command-here`

浙公网安备 33010602011771号