1

I want to run YII_ENV=prod yii kw/test ten times. I tried

$ YII_ENV=prod for x in 1..10 do; yii kw/test done;
-bash: for: command not found
1304682651

(Seemed to run once.) I also tried

$ for x in {1..10} do; YII_ENV=prod yii kw/test done;
-bash: syntax error near unexpected token `YII_ENV=prod'

GNU bash, version 4.3.39(2)-release (i686-pc-cygwin)

  • 2
    Insert a ; before done. – Cyrus Feb 27 '16 at 19:56
  • 6
    I think you just have misplaced semicolons? Try for x in {1..10}; do YII_ENV=prod yii kw/test; done – Celada Feb 27 '16 at 19:57
3

First correct the syntax of your command, place the semicolons correctly. Instead of:

for x in 1..10 do; yii kw/test done;

Use (adding a correct brace expansion also):

for x in {1..10}; do yii kw/test; done

Then, add the variable:

for x in {1..10}; do YII_ENV=prod yii kw/test; done
5

The syntax VARIABLE=VALUE COMMAND to set an environment variable for the duration of a command only works when the command is a simple command (more precisely, an external command or a builtin that acts like one — see When can I use a temporary IFS for field splitting? for more details). You can't use it with a complex command such as a for loop.

Your first attempt failed because for wasn't the first word of a command, so it wasn't parsed as a keyword, so bash looked for a command called for instead of parsing a for loop. Your second attempt failed because of a simple syntax error in the loop: you need a semicolon or line break before do, again because otherwise do isn't recognized as a keyword. Similarly you also need a semicolon before done.

for x in {1..10}; do YII_ENV=prod yii kw/test; done

To set a variable for the duration of the loop, if you don't care about overwriting a previous value, just set the variable and unset it afterwards.

export YII_ENV=prod
for x in {1..10}; do yii kw/test; done
unset YII_ENV

Alternatively, run the loop in a subshell. This is an option only if the loop isn't supposed to modify the shell's environment.

(
  export YII_ENV=prod
  for x in {1..10}; do yii kw/test; done
)

Alternatively, run the loop in a function, and make the variable local to the function. This requires bash or ksh or zsh, it doesn't work in plain sh, but the {...} syntax has those requirements anyway.

call_yii () {
  typeset YII_ENV=prod
  export YII_ENV
  for x in {1..10}; do yii kw/test; done
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.