使用变量在 bash 中编写 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13085253/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a for loop in bash using a variable
提问by Kr?lleb?lle
I want to create a for loop in bash that runs from 1 to a number stored in a variable in bash. I have tried doing what the answer to thisquestion tells, but it produces this error:
我想在 bash 中创建一个 for 循环,该循环从 1 运行到存储在bash. 我已尝试按照此问题的答案进行操作,但会产生此错误:
Syntax error: Bad for loop variable
My OS is Ubuntu 12.04 and the code looks like this:
我的操作系统是 Ubuntu 12.04,代码如下所示:
#!/bin/bash
TOP=10
for ((i=1; i<=$TOP; i++))
do
    echo $i
done
What does this error message mean? Here is an output image:
这个错误信息是什么意思?这是一个输出图像:


回答by divanov
C-style for loop works only in few shells and bash is among them. This is syntax is not part of POSIX standard.
C 风格的 for 循环仅适用于少数 shell,而 bash 就是其中之一。这是语法不是 POSIX 标准的一部分。
#!/bin/bash
TOP=10
for ((i=1; i<=$TOP; i++))
do
    echo $i
done
POSIX-compliant for loop will be the following
符合 POSIX 的 for 循环如下
#!/bin/bash
TOP=10
for i in $(seq 1 $TOP)
do
    echo $i
done
This works both in bash and sh.
这在 bash 和 sh 中都有效。
To know which shell you are logged in, execute the following command
要知道您登录的是哪个 shell,请执行以下命令
ps -p $$
Where $$ is PID of current process and the current process is your shell, and ps -pwill print information about this process.
其中 $$ 是当前进程的 PID,当前进程是您的 shell,ps -p并将打印有关此进程的信息。
To change your login shell use chshcommand.
要更改您的登录 shell,请使用chsh命令。
回答by Paolo Moretti
You are running the script with sh, not bash.
Try:
您正在运行脚本sh,而不是bash。尝试:
bash split_history_file_test.sh
回答by Karoly Horvath
This code doesn't produce that error. The bash version shipped with that ubuntu version should execute it without problems.
此代码不会产生该错误。该 ubuntu 版本附带的 bash 版本应该可以毫无问题地执行它。
Note: you want to echo $i.
注意:你想要echo $i.

