![](/img/trans.png)
[英]Unexpected end of file error in bash script (Makefile) nested for-loop
[英]Writing a bash for-loop with a variable top-end
我經常使用眾所周知的語法在bash中編寫for循環:
for i in {1..10} [...]
現在,我正在嘗試編寫一個由變量定義頂部的示例:
TOP=10
for i in {1..$TOP} [...]
我嘗試過各種括號,大括號,求值法等,通常會返回錯誤“替換錯誤”。
如何編寫我的for循環,使限制取決於變量而不是硬編碼值?
您可以使用像這樣的for循環來迭代變量$TOP
:
for ((i=1; i<=$TOP; i++))
do
echo $i
# rest of your code
done
如果您有gnu系統,則可以使用seq
生成各種序列,包括此序列。
for i in $(seq $TOP); do
...
done
答案部分存在 :請參見示例11-12。 C樣式的for循環 。
以下是摘要,但請注意,問題的最終答案取決於您的bash解釋器( / bin / bash --version ):
# Standard syntax.
for a in 1 2 3 4 5 6 7 8 9 10
# Using "seq" ...
for a in `seq 10`
# Using brace expansion ...
# Bash, version 3+.
for a in {1..10}
# Using C-like syntax.
LIMIT=10
for ((a=1; a <= LIMIT ; a++)) # Double parentheses, and "LIMIT" with no "$".
# another example
lines=$(cat $file_name | wc -l)
for i in `seq 1 "$lines"`
# An another more advanced example: looping up to the last element count of an array :
for element in $(seq 1 ${#my_array[@]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.