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

7,205

Solution 1

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

Solution 2

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
}
Share:
7,205

Related videos on Youtube

Chloe
Author by

Chloe

Updated on September 18, 2022

Comments

  • Chloe
    Chloe over 1 year

    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)

    • minorcaseDev
      minorcaseDev about 8 years
      Insert a ; before done.