[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] confuse about bash

From: Greg Wooledge
Subject: Re: [Help-bash] confuse about bash
Date: Mon, 20 Feb 2012 08:11:58 -0500
User-agent: Mutt/

On Sun, Feb 19, 2012 at 09:29:48AM +1100, PurencoolGmail wrote:
> I have a bash script that says this
> HOUSE=null;
> echo HOUSE;
> What I am trying to do from the command line is set variable when the 
> script
> loads but I can't seem to fined anything on the web about it.

If those two lines are the literal content of the script, then changing
the value of the variable wouldn't accomplish anything, because the
variable isn't actually being used.  The echo command is going to write
the literal string "HOUSE" no matter what.

> I was 
> hoping to
> to something like this
> > bash set HOUSE=foo
> Is this possible?

You would have to change the script.  The script is overwriting the
value of HOUSE with the literal string "null".  If you want the script
to accept the value of HOUSE from the environment, and only set it to
"null" if it was not in the environment to begin with, then you can use
something like this:

#!/usr/bin/env bash
: ${HOUSE:=null}
echo "HOUSE is $HOUSE"

Testing it:

imadev:~$ ./foo
HOUSE is null
imadev:~$ HOUSE=73 ./foo
HOUSE is 73

The : ${HOUSE:=null} idiom is a bit confusing at first.  The : is a command
that does nothing.  The ${...} is a parameter expansion with possible side
effects.  Here, we only want the side effects -- not the value of the
expansion (which is why we use that expansion as an argument to a command
that does nothing).

The ${HOUSE:=null} expansion says "if HOUSE is unset, or is empty, then
put null into it".  It then expands to the (possibly new) value of $HOUSE,
which we discard (with the : command).

reply via email to

[Prev in Thread] Current Thread [Next in Thread]