Home > Mobile >  ASH/BASH in Alpine: how to expand a variable from a list of variable names read from a list file
ASH/BASH in Alpine: how to expand a variable from a list of variable names read from a list file

Time:11-15

I've been trying to figure out a way to expand a variable from a string (the variable name) read from a list within a file.

The objective here is to evaluate if all variables in a gitlab pipeline are present, if not, fail the pipeline.

The best possible solution would be to have this as an one-liner and working from Alpine's ash shell, but a bash -c "something something" could also do.

Clearly there's a problem with the (!) expansion character as the varcontent is always empty, but I just can't figure out what I'm doing wrong.

alpine314:~# cat checkvars.sh
#!/bin/bash
false=false
while read -r line; do
    varcontent=${!line}
    if [ -z "$varcontent" ]; then
        echo "Error: Missing a required pipeline variable."
        false=true
        exit 1
    else
        echo "$line: $varcontent"
    fi
done < $1
alpine314:~# cat varsfile
VAR1
VAR2
VAR3
alpine314:~# echo $VAR1
1
alpine314:~# echo $VAR2
2
alpine314:~# echo $VAR3

alpine314:~# bash -x checkvars.sh varsfile
  false=false
  read -r line
  varcontent=
  '[' -z '' ']'
  echo 'Error: Missing a required pipeline variable.'
Error: Missing a required pipeline variable.
  false=true
  exit 1
alpine314:~#

The desired behavior here is to exit the script with an error in case any of the variables are empty/not set.

Cheers!

CodePudding user response:

what I'm doing wrong.

Your variables are not exported. Run the following before running your scirpt.

 export VAR1 VAR2 VAR3

Check your scripts with shellcheck. false=true - would be better to use a different variable name...

  • Related