1

With bash, I'm trying to set environment variables for a given command by injecting another variable before running said command:

It's easier to describe that with an example:

setHELLO="HELLO=42"
${setHELLO} echo ${HELLO}

I would expect this script to output 42, instead I get an error line 2: HELLO=42: command not found

Precision: While here I could simply write

HELLO=42
echo ${HELLO}

I'm aiming to not provide all env variables to all commands in my shell script, which is why I'm setting the env variable explicitly right in the line where I run the command (echo ${HELLO})

I'm also aiming to not repeat the variable value declaration, by not re-declaring in front of each command like this:

HELLO=42; echo command1
HELLO=42; echo command2
HELLO=42; echo command3
Nicolas Marshall
  • 4,186
  • 9
  • 36
  • 54
  • 1
    You can not expect `HELLO=42 echo ${HELLO}` to print 42. See [this post](https://stackoverflow.com/questions/36380569/prefixing-variable-assignment-doesnt-work-with-echo). Does this invalidate the question? – that other guy Jan 13 '21 at 00:27
  • @thatotherguy It invalidates what I thought I knew, but brings more questions ! I fixed the last code block to be what I intended – Nicolas Marshall Jan 13 '21 at 13:03
  • Also, about the duplicates, while both useful, the first one has the declaration directly in-line rather than as a variable itself, and the second one is global. Can we keep this question as the answer is more complete and helpful in my case ? – Nicolas Marshall Jan 13 '21 at 13:05

1 Answers1

1

Put a semicolon in there and you're good. If you want to not corrupt local variables in your script env, use a function or use a subshell

Semi-Colon

HELLO=69
setHELLO='let HELLO=42'
( ${setHELLO}; echo ${HELLO} ) # 42
( ${setHELLO}; echo ${HELLO} ) # 42
( ${setHELLO}; echo ${HELLO} ) # 42
echo $HELLO                    # 69

Function

sayHello() {
    local HELLO=42
    echo ${HELLO}   # 42
    echo ${HELLO}   # 42
    echo ${HELLO}   # 42
}

HELLO=69
sayHello      # 42, 42, 42
echo ${HELLO} # 69

Sourced bash script

#---------------
# This script is called sayHello.sh
echo $HELLO
#---------------

# From some other script/cmdline
HELLO=69
setHELLO='HELLO=42'
${setHELLO} source sayHello.sh  # 42
${setHELLO} source sayHello.sh  # 42
${setHELLO} source sayHello.sh  # 42
echo $HELLO                     # 69