help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] ${var:?message} customization


From: Matias A. Fonzo
Subject: Re: [Help-bash] ${var:?message} customization
Date: Thu, 14 May 2015 18:22:56 -0300

Hello Greg,

El Thu, 14 May 2015 08:23:26 -0400
Greg Wooledge <address@hidden> escribió:
> On Wed, May 13, 2015 at 08:54:09PM -0300, Matias A. Fonzo wrote:
> > Normally, "${var:?'message'}" display error if null or unset if
> > 'message' is omitted. But if it is not, a particular message can be
> > included, in any case, shows (e.g):
> > 
> >   myscript: line 2: var: parameter null or not set
> > 
> > My question is, there is a way to print only the message? (removing
> > myscript: line number: var:)
> 
> Are you just asking "How can I write a message if a variable is unset,
> or set to an empty string?"
> 
> if [ -z "$var" ]; then
>     echo "var is either empty or unset"
> fi
> 
> If you want to distinguish between "unset" and "set to an empty
> string", you can use a more subtle test:

Not really, what I have is a simple function to check if a variable is
empty or unset (without distinction)[1] for handling positional
parameters (arguments, options).  If I can do a simple check taking the
approach of parameter expansion, I would avoid the function call.

[1]
_checkArgument() {
  if [ "$1" = "" ] ; then       # Report empty argument.
    echo "bootstrap: '${2}' requires an argument. See 'bootstrap
    --help'" 1>&2
    exit 1
  fi
}

while [ "$1" ] ; do
  case "$1" in
    -s)
      stage="$2"
      _checkArgument "$stage" '-s'
      shift 2
      ;;
    *) break;
  esac
done

> if [ "${var+defined}" ]; then
>     if [ -z "$var" ]; then
>       echo "var is set to an empty string"
>     else
>       echo "var is set to a non-empty string"
>     fi
> else
>     echo "var is unset"
> fi
> 
> (That's all using POSIX sh syntax.  Recent versions of bash have a
> "test -v" command, but I don't think it adds much utility.)
> 

Thanks for the examples, comments.




reply via email to

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