Search code examples
shellcshtcsh

Overriding an user defined variable/environment variable through command line option


Looking for ways to override a c-shell variable from command line. In the script (test.csh) below, the default value of FOO will be 0. I should "optionally" be able to override the value of FOO from command line.

#!/bin/csh

setenv FOO 0
if (${FOO}) then
    echo "Hello"
else
    echo "World"
endif

Looking at the man pages of csh/tcsh indicates there is a -Dvariable[=value] would do that. So I tried the below on command line and thought it would print "Hello". Instead, it printed "World" - which means -DFOO=1 is NOT taking effect.

unix-prompt> ./test.csh -DFOO=1

I do NOT want to use #argv thing, and then parse the args and set environment variable appropriately based on the args. There is NO compulsion for me to use setenv.

The expectation is to override the default value that is being used in c-shell, using a command-line override.


Solution

  • The -D option is documented in tcsh(1) as:

       -Dname[=value]
           Sets the environment variable name to value. (Domain/OS only) (+)
    

    I'm going to guess you're not running Domain/OS :-)

    You can use env to set a variable for one command, for example:

    $ env FOO=1 ./a.csh
    

    Note that in your script you're always overriding FOO to be 0; so you'll need to modify that to override it just when it's not set:

    if (! $?FOO) setenv FOO 0
    

    As a postscript, I should point out that scripting in csh is generally discouraged if it can be avoided; there are many caveats and shortcomings (see e.g. this) and you're almost always better off using a Bourne shell.