help-bash
[Top][All Lists]
Advanced

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

Re: Using opt="on" versus opt=true


From: Greg Wooledge
Subject: Re: Using opt="on" versus opt=true
Date: Tue, 6 Apr 2021 17:49:09 -0400

On Tue, Apr 06, 2021 at 11:34:19PM +0200, pauline-galea@gmx.com wrote:
> I have a bash script that parses options.
> 
> Am using the following expression to know if the option is enabled.
> opt="on"
> 
> Would it be easier to use
> opt=true

You're basically asking how to implement boolean variable types in bash.
There are several ways.  Using human-readable strings is one of them,
and some people do that.

My preference is to use integer values, as one does in C.

opt=0
while true; do
  case $1 in
    -o) opt=1;;
    ...
  esac
  shift
done

if ((opt)); then
  do_stuff
fi

There's a third option that some people use, which involves sticking
the names of commands into the boolean variables, and then *executing*
the variables.  I do not recommend this.  It's far too easy to do massive
damage to things if one of the variables picks up a stray value.



reply via email to

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