Linux Format

★ Script configurat­ion

-

I am a newbie at making Bash scripts, but I was wondering if it’s possible to store, recall and modify variables for use in Bash scripts inside of a config file? Jules Kemp Reading variables from a config file in the shell is easy. Create a file containing the variable assignment­s; the same as if you had them in the script itself FOO="bar" XYZ="abc" then run the file in the context of the current shell with the source command source myvars.cfg

When you run a shell script, it’s run as a subshell, so any changes it makes to the environmen­t are lost when it exits. Running it with source runs it in the current shell, just the same as if you had typed the commands directly. This applies to both scripts and an interactiv­e shell. To see this, create the above file then run: $ XYZ="123" $ echo $XYZ $ bash myvars.cfg $ echo $XYZ

You will see that the value of XYZ in the current shell doesn’t change, despite it being changed in the config file. Now replace Bash with source on the third line and try again to see the difference.

Writing the values can be achieved with a loop, using a list of variable names: for _VAR in FOO BAR XYZ ETC do eval _VAL=\$$_VAR echo "$_VAR=\”$_VAL\"" done >myvars.cfg.new mv myvars.cfg.new myvars.cfg

The first line loops through a list of variable names. Line three assigns the contents of the variable _VAR to _VAL – there’s no magic behind the leading underscore; it just minimises the risk of these temporary variable names colliding with one used by your script. A $$ is normally interprete­d by the shell as the PID of the current process, the backslash ( \ ) escapes that, so you end up with $ followed by the value of $_VAR , eg $FOO. The eval statement assigns this to a second temporary variable. Then we simply echo the variable name, an equals sign ( = ) and the variable’s contents enclosed in double quotes ( "" ) which we also have to escape with backslashe­s.

We redirect the output from this loop to a temporary file, then rename that file over the original. We use a temporary file in case something goes wrong in the loop. That way you still have the original settings. There’s more you can add to this, eg checking to see if any variables have been modified and only writing them out if so, but this is enough to get you going.

Newspapers in English

Newspapers from Australia