[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Using opt="on" versus opt=true
From: |
Koichi Murase |
Subject: |
Re: Using opt="on" versus opt=true |
Date: |
Wed, 7 Apr 2021 09:35:16 +0900 |
2021年4月7日(水) 6:49 Greg Wooledge <greg@wooledge.org>:
> My preference is to use integer values, as one does in C.
>
> opt=0
> while true; do
> case $1 in
> -o) opt=1;;
An interesting topic. I often use a modified version of this. I
initialize `opt' with *an empty string* and then assign *1* when it is
enabled. In this way, one can use `opt' both in the conditional [[
$opt ]] and in arithmetic expressions ((opt ? expr1 : expr2)), etc.
(Note that when a single word is specified to [[ ]], it tests if the
word is empty or not. Note also that empty strings are usually
evaluated as 0 in the arithmetic context). To test the value, I
basically use [[ $opt ]] but sometimes use it in the arithmetic
context when it involves other arithmetic expressions.
function readargs {
while (($#)); do
local arg=$1; shift
case $arg in
(-o) opt_foo=1 ;;
(-p) opt_bar=1 ;;
# ...
esac
done
}
opt_foo= opt_bar=
readargs "$@"
[[ $opt_foo ]] && do_something
[[ $opt_bar ]] && do_another_thing
----
For another way, when there are many options, I sometimes use what I
call ``flags'' which is similar to the shell special variable $-. I
prepare a single empty variable `flags=' and append a character
corresponding to each option. The option corresponding to the
character `c' can be tested by [[ $flags == *c* ]].
function readargs {
while (($#)); do
local arg=$1; shift
case $arg in
(-o) flags+=f ;;
(-p) flags+=b ;;
# ...
esac
done
}
flags=
readargs "$@"
[[ $flags == *f* ]] && do_something
[[ $flags == *b* ]] && do_another_thing
----
When there are even more options, I use what I call ``opts'' which is
similar to $SHELLOPTS and $BASHOPTS and is a colon-separated list of
words. This can be tested by [[ :$opts: == *:word:* ]].
function readargs {
while (($#)); do
local arg=$1; shift
case $arg in
(-o) opts+=:foo ;;
(-p) opts+=:bar ;;
# ...
esac
done
}
opts=
readargs "$@"
[[ :$opts: == *:foo:* ]] && do_something
[[ :$opts: == *:bar:* ]] && do_another_thing
--
Koichi