On Wed, Aug 04, 2021 at 08:47:30PM -0700, Gary L. Roach wrote:
> Thanks for the help but I still have the problem of the if statement
> always being true. This time I enclosed the file so you can test it.
Please, don't top quote. It confuses the hell out of me.
Now, I think in your script
if test A="0 ; "
should read
if test "$A" = "0 ; "
or, in the square bracket version:
if [ "$A" = "0 ; " ]
Basically, I'm repeating what Greg wrote, in somewhat other words. Greg's
mails are worth being read twice or three times.
Look carefully. Note a couple of things:
** white spaces around the "=":
`test' and its fancy cousin `[' are regular programs [1] invoked
by the shell: what follows are arguments which get interpreted by
`test', in this case, the args are "$A", = and "0 ; ", i.e. the
first arg, an operator (=) and the second arg. As always in the
shell, the args HAVE TO BE SEPARATED BY WHITESPACE (huh sorry for
raising my voice :)
** shell is not your regular php
the shell's power (and strangeness) derives from its text replacement
model. You have to bear that in mind. When the shell processes a
line, it does text replacements until it thinks it's ready, then
it invokes the command (typically a binary somewhere in $PATH, but
it can be a builtin, an alias or a function). In your case:
if test "$A" = "0 ; "
transforms to
if test "0 ; " = "0 ; "
...so the binary `test' gets to see three args (due to the quotes).
It dutily finishes with exit code 0, meaning "okidoki".
** watch those quotes
this follows a bit from the above. Imagine what happens if you lose
the quotes around "$A":
if test $A = "0 ; "
now transforms to
if test 0 ; = "0 ; "
Now test sees *four* arguments: "0", ";", "=" and "0 ; ". this
confuses the hell out of it and it balks at you:
bash: test: too many arguments
Shell programming is a tad different than Python, Perl, Ruby or what
you have. The textual replacement model takes some thought, but it
rewards you (as long as you use shells for what they were meant to).
I hope that gets you on track :)
And oh, in things shell, read Greg's mails. Perhaps also his wiki [2].
Cheers
[1] Nowadays this is a little white lie: most shells have them
as builtins, but they are supposed to behave like regular
programs, for compat. There /is/ a /bin/test, but I can't
find a /bin/[ on my system anymore.
[2] https://mywiki.wooledge.org/BashGuide/
-- tomás
Attachment:
signature.asc
Description: Digital signature