Sujet : Re: Checking for right # of args in a shell script (Was: a sed question)
De : janis_papanagnou+ng (at) *nospam* hotmail.com (Janis Papanagnou)
Groupes : comp.unix.shellDate : 20. Dec 2024, 16:49:50
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vk43n0$3gtg6$1@dont-email.me>
References : 1 2 3
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.8.0
On 20.12.2024 16:11, Kenny McCormack wrote:
In article <vk40gi$3g9sm$1@dont-email.me>,
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
On 18.12.2024 20:46, Salvador Mirzo wrote:
[...]
>
First (before I forget it) change your string comparison '<' to the
numerical comparison operator '-lt' as in: test $# -lt 2 && usage
Otherwise, if you get used to using the wrong operator, you may get
subtle errors in future if you continue that habit.
Agreed, in general, but in practice, the need rarely arises.
I certainly disagree on this; if you have 10..19 (or 100..199 etc.)
arguments the '<' test just doesn't trigger but '-lt' does. I mean,
why use a wrong operator. If it will only in specific cases produce
correct results, or if it produced in most cases correct results;
it's just the wrong thing.
The idiomatic way to do this is just:
[ $# = 2 ] || usage()
Yes, but I don't use that but prefer (like you) [[...]], an in, say,
[[ $# == 2 ]] || usage
(since I use Kornshell's [[...]] I also use its "modern" '==').
Also, when I need to do more complex arg verification, I use bash's [[ ]]
mechanism (Yes, I know OP is using /bin/sh, but there is no reason nowadays
not to use bash).
If the OP is on Linux the 'sh' might actually be a Bash. If he's,
say, on an AIX the 'sh' may actually be a 'ksh'. - So in any case
there's a good chance to have [[...]] supported. - But it's true
that if he specifies /bin/sh he should not rely on something else
than a POSIX shell (at least).
Say I want there to be 2 or 3 args (no other # is
acceptable and the 2nd arg must be numeric. Like this:
[[ $#,$2 =~ ^[23],[0-9]+$ ]] || { echo "Arg error!"; exit; }
An interesting pattern!
Usually I'm spoiled by Kornshell's 'getopts' feature. As I'm using,
say "s:" in an optstring for an option '-s' with a string argument
I'm just using "i#" for an option '-i' with a numeric argument.
(For simple cases with few options I typically don't use 'getopts',
though; I'm lazy.)
Janis