是否有可能在bash中運行循環遍歷多個目標?或者我需要訴諸嵌套for循環?是否有可能在bash中運行for循環來迭代多個目標?
例如:
for i in *.config,*.command; do
echo "Do something"
done
感謝。
是否有可能在bash中運行循環遍歷多個目標?或者我需要訴諸嵌套for循環?是否有可能在bash中運行for循環來迭代多個目標?
例如:
for i in *.config,*.command; do
echo "Do something"
done
感謝。
可以使用
for i in `ls *.config *.command`
do
echo "hhhh"
done
在這裏使用'ls'有什麼意義? shell不會浪費寶貴的CPU週期,而不會分配「ls」。 – Jens 2013-03-27 15:16:27
-1究竟是什麼**不要做**:在反引號中解析'ls'! – 2013-03-27 15:24:24
反引號'用於舊式命令替換。建議使用'foo = $(command)'語法。 '$()'中的反斜槓處理並不令人驚訝,並且更容易嵌套。見http://mywiki.wooledge.org/BashFAQ/082 – 2013-03-27 15:24:45
讓文件尋找一個數組聲明中展開。
$ touch {1..5}.txt
$ touch {1..5}.cfg
# use nullglob
$ shopt -s nullglob
$ list=(*.txt *.cfg)
# loop over all elements in array
$ for file in "${list[@]}"; do echo "$file"; done
1.txt
2.txt
3.txt
4.txt
5.txt
1.cfg
2.cfg
3.cfg
4.cfg
5.cfg
# number of items
$ echo "${#list[@]}"
10
如果你的意圖有通過命名文件迭代\ *。配置和\ *。命令,是的,它會工作,但只有當你刪除逗號,並用其替換空間。 (列表以空格分隔。)但是,如果沒有xxxx.config文件,我將設置爲「* .config」,除非先執行'shopt -s nullglob'。 (或'shopt -s failglob',如果你想讓它產生一個錯誤。) – William 2013-03-27 15:20:27
你是什麼意思「迭代通過多個目標」?目標通常是「做」的事情。 shell處理命令和參數。 – Jens 2013-03-27 15:21:16
按目標我的意思是.command,.config,.whatever文件。我不確定如何更好地表達我的問題的性質。如果我使用「參數」一詞,我認爲人們會對i迭代器而不是實際目標(.config,.command)感到困惑。你的解決方案奏效,謝謝。 – Karimi 2013-03-27 15:30:38