Skip to content
Advertisement

Variable passed through environment not available in script

I’m trying to write an if/elif/else statement where if a variable equals “Full” it will cat a file and if the same variable equals “Quick” it will read a different, smaller file. The variable is being set outside of the script and is being exported by export var1=Quick

I have

#!/bin/sh
echo $var1
export $var1=var1
{
#try cat-ing the file. If it cannot be read, exit with error. 
if [ "$var1" = "Full" ];
then 
echo "Full read chosen"
cat foo
exit 0
elif [ "$var1" = "Quick" ];
then
echo "Quick read chosen"
cat bar
exit 0
else
echo "Please choose quick or full"
exit 1
fi
}

When I try to run the script by calling ./test, it doesn’t seem like the variable is being set

+ '[' '' = Full ']'
+ '[' '' = Quick ']'
+ echo 'Please choose quick or full'
Please choose quick or full
+ exit 1

Is there a reason why, even though the variable is exported outside of the script, the variable isn’t being passed to the script?

Advertisement

Answer

The following absolutely does work:

$ export var1=Quick
$ ./yourscript

…where yourscript is the script in question.

As such, your question needs to be adjusted to contain enough information and details to reproduce the problem.


As an aside, your script would be better written thusly:

#!/bin/sh
case $var1 in
  Full)
    echo "Full read chosen" >&2
    cat foo
    ;;
  Quick)
    echo "Quick read chosen" >&2
    cat bar
    ;;
  *)
    echo "Please choose quick or full" >&2
    exit 1
    ;;
esac
exit 0

Both of the following work for me:

$ var1=Quick ./yourscript
Quick read chosen
cat: bar: No such file or directory
$ (export var1=Quick; ./yourscript)
Quick read chosen
cat: bar: No such file or directory
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement