How to pass Named Variable to script

How to do things, solutions, recipes, tutorials
Post Reply
Message
Author
kethd
Posts: 451
Joined: Thu 20 Oct 2005, 12:54
Location: Boston MA USA

How to pass Named Variable to script

#1 Post by kethd »

How to pass named variables to ash/bash shell scripts

If you want to test a shell script that uses named variables, with values passed in from the outside, things are somewhat confusing.

If you just set a value:
# SBUG=trying
and then run your script:
# ash testscript
you'll be surprised to find that $SBUG is null, empty.

The reason is that the value that you set exists only at that level, and your testscript ran as a nested sub-shell, one level down.

To make this work, use the export command:
# export SBUG=newval -- or just:
# export SBUG
which will make the named variable available at that level, and all nested levels below (but not at any levels above). If you change the value at any of nested levels below, the new value will be inherited by any levels below that, but levels above will retain their previous values.

You can view named variables with the set or env commands. The set command gives a nice ordered list, but it includes both "environment" variables and some kind of "other" values. The env command seems to show a more limited list, in hodge-podge order. Using these commands inside of test scripts can help you understand what values they are seeing.

(This is not the standard way to pass arguments to scripts. The normal way is with in-line positional arguments, $1 $2 $3 etc.)

Post Reply