shell基礎(chǔ)
我們知道Shell腳本中的循環(huán)指令有:while碉纺、for 和 until loops。
一般比較常用的是 while
和 for
焚鹊,舉幾個常用例子:
#!/usr/bin/env bash
start=1
end=6
while [ ! ${start} -eq ${end} ]; do
echo ${start}
let start++
done
# 各輸出 1 2 3 4 5
for i in 1 2 3 4 5; do
echo ${i}
done
# 各輸出 1 2 3 4 5
# 1 2 3 4 5 也可以寫成 {1..5} 或 `seq 1 5`
for color in red orange yellow; do
echo ${color}
done
# 各輸出 red orange yellow
for file in `ls`; do
echo ${file}
done
# 打印腳本所在目錄下的文件名
# 省略或者 in $@ 作用是打印參數(shù)列表
counter=0
for files in *; do
# increment
counter=`expr $counter + 1`
done
echo "There are $counter files in ‘`pwd`’"
# 計算腳本所在目錄下的文件個數(shù)
counter=0
for ((x=0;x<=5;x++)); do
let counter=counter+x
done
echo $counter
# 輸出15
# 計算 1..5 的和
除了以上的幾種循環(huán)用法之外腕够,用循環(huán)可以對文本進行逐行讀取,再配合其它的指令可以實現(xiàn)更加靈活的功能优质。例如:
#!/usr/bin/env bash
old_ifs=${IFS}
IFS=":"
cat /etc/passwd | while read name passwd uid gid description home shell; do
echo -e ${name}"\t"${passwd}"\t"${uid}"\t"${gid}"\t"${description}"\t"${home}"\t"${shell}
done
IFS=${old_ifs}
# 打印系統(tǒng)的用戶
通過管道將文本傳遞給 read
指令竣贪,再賦值給對應(yīng)的變量,實現(xiàn)更加靈活的用法巩螃。借此拋磚引玉演怎,希望讀者能夠自行探索實現(xiàn)更多好玩有趣的想法。
end.