Re: Improper handling of \! and \( while using Bash V4.1.2

2018-08-06 Thread Greg Wooledge
On Mon, Aug 06, 2018 at 04:14:49PM +0530, anant garg wrote:
> $ mode=!
> $ [ "$mode" != "ro" -a "$mode" != "rw" ] && echo OK
> + '[' '!' '!=' ro -a '!' '!=' rw ']'
> bash: [: too many arguments

The use of -a and -o as conjunctions inside a test or [ command is to
be avoided.  It's not POSIX compatible, and as you have now observed
first-hand, even in bash, it is perilous.

For this particular check, I would use case:

  case $mode in
ro|rw)  ;;
*)  ;;
  esac

But if for some reason you've got an if-boner, you could either use
two separate test commands:

  if [ "$mode" != ro ] && [ "$mode" != rw ]

or use bash's [[ command:

  if [[ $mode != ro && $mode != rw ]]

The former is POSIX comptaible.  The latter is, of course, a bash extension.



Improper handling of \! and \( while using Bash V4.1.2

2018-08-06 Thread anant garg
Hi ,

I am using the below environment.

Linux kernel :- kernel-2.6.32-504.16.2.el6.x86_64
Bash version :- bash-4.1.2-29.x86_64

In our production code, one test related to parameter validation failed as
below :-

$ mode=!
$ [ "$mode" != "ro" -a "$mode" != "rw" ] && echo OK
+ '[' '!' '!=' ro -a '!' '!=' rw ']'
bash: [: too many arguments

I checked the source and found that when multiple checks are done in one
single test expression then ! parsing fails.

For eg, the below works :-
$ mode=!
$ [ "$mode" != "ro" ] && echo OK
OK

The below also works :-
$ mode=\!
$ [ "$mode" != "ro" ] && echo OK
OK


The below also works :-
$ mode=\(
$ [ "$mode" != "ro" ] && echo OK
OK


but when below is run where multiple conditions are tested, then the
parsing fails.

For eg:-
mode=\(
[ "$mode" != "ro" -a "$mode" != "rw" ] && echo OK
bash: [: `)' expected, found ro

I tried testing with other special characters as well, but this issue came
with only !,\! or \(.

When I tested with extended test i.e [[ , this issue did not came.
Was there any known bug in Bash V4.1.2 related to parsing of multiple ! or
\( in [.