0

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

1
  • 1
    Run your code through shellcheck.net. Commented Jun 8, 2015 at 20:13

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

If you want to test for integer equality, you should use -eq. For strings, use =. == is supported by bash but not other shells.
Thank you very much for your thoughts, that's exactly what i was looking for . thanks
@Tom Fenech: point taken. I've changed [ .. ] to (( .. ))
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.