Danilo Danilo - 6 months ago 15
Bash Question

Persist variable in success or fail shell command

I have the following program.sh:

#!/bin/bash

(true && { echo true1; echo true2; TEST=1; } || { echo false1; echo false2; TEST=0; }) >> program.log

echo test: $TEST


Why the output of program.sh is:

test:


What is a workaround to persist value in TEST?

Answer

Using parentheses creates a subshell. Variable assignments in a subshell don't propagate back to the parent shell. Try replacing () with {}.

{ true && { echo true1; echo true2; TEST=1; } || { echo false1; echo false2; TEST=0; }; } >> program.log