I expect the following snippet
until [ MY_VAR=$(echo my_var_val) ]
do
echo 'inside the loop'
done
echo $MY_VAR
to produce the my_var_val
output. However, this does not happen. How can I make this happen?
Long story
I want to perform a retry on a script producing some output. I need the output later in the script. Unfortunately, assigning the variable value in the until test fails - the variable has empty value, when I try to use it later in the script. How can I execute the external script with retry logic and have its output stored in a variable that I can use later in the script?
max_retry=10
counter=0
until [ IMPORTANT_SCRIPT_OUTPUT=$(python very_important_script_with_output.py) ]
do
#retry logic
if [[ counter -eq $max_retry ]]; then
echo "Failed"
exit 1
fi
((counter ))
echo "very_important_script_with_output failed, retrying"
done
python another_very_important_script_with_the_previous_script_output_as_parameter.py --important-parameter $IMPORTANT_SCRIPT_OUTPUT
CodePudding user response:
You can try this:
until MY_VAR=$(echo my_var_val); test -n "$MY_VAR"
do
echo 'inside the loop'
done
echo $MY_VAR
CodePudding user response:
[
is an ordinary command, not shell syntax, and its arguments are processed normally. So MY_VAR=$(echo my_var_val)
is just a string beginning with MY_VAR=
, not a variable assignment.
Do the assignment separately from testing the variable.
while :
do
MY_VAR=$(command)
if [[ -n "$MY_VAR" ]]
then break
fi
echo 'inside the loop
done