BASH: testing the number of arguments passed in an IF statement

87 Views Asked by At

i'm trying to send two arguments to .run file. $2 default should be 0.

if $2 arg = 1 then

grep -i a -1 --color -E $1 *.*

else

grep -i --color -E $1 *.*

, something like this

if [${2:-0} = 1] then
  grep -i a -1 --color -E $1 *.*
else
  grep -i --color -E $1 *.*
fi

but it didn't seem to work ? any ideas ?

thanks

2

There are 2 best solutions below

3
On BEST ANSWER

Your question leaves a bit of guess work as to what you are trying to do. You you don't use $2 anywhere, so you just want to use that as a flag to decide to run grep in a different way? If so, use $# will tell you how many arguments were passed. To test if there are two of them, you could use (( $# = 2 )).

As Tom Fenech suggested, you have a syntax errors in your code. There should be a semicolon after the ] or then should be put on a new line. Also, I believe you need spaces after [ and before ]. So here's a guess of what you might have been trying to do:

if (( $# == 2 ));  then
  grep -i a -1 --color -E $1 *.*
else
  grep -i --color -E $1 *.*
fi
0
On

Brackets are not just syntax: [ is actually a command, so it requires whitespace to separate it from its arguments:

if [ ${2:-0} = 1 ]; then

https://www.gnu.org/software/bash/manual/bashref.html#index-test