How do I use a temporary environment variable in a bash for loop?

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)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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
}

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x