0

I'm trying to write out a script that will automate one of my more tedious tasks. I've pretty much got everything down and can get the individual components of code to do what I want them to, but I'm running into trouble trying to get the if statement to work. Here's what I'm trying to do:

if [ ack --ignore-case 'foo' ]; then
    Do this action
else
    Do that action
fi

As of now it always does the else action, even if the ack parameter is true.

Thanks!

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
I Dabble
  • 321
  • 2
  • 11

2 Answers2

3

Just drop the square brackets

if ack --ignore-case 'foo' ; then
    Do this action
else
    Do that action
fi

You don't want to check that the string ack --ignore-case 'foo' is non-empty, you want to check ack's exit status.

You should have recieved a warning telling you so:

-bash: [: --ignore-spaces: binary operator expected
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
choroba
  • 231,213
  • 25
  • 204
  • 289
2

Remove the [ - you want to check the exit status of ack:

if ack --ignore-case 'foo'; then

ack returns a 0 (success) exit status if a match is encountered.

Although it may look like a syntactical construct, [ is in fact a function (synonymous with test), which returns 0 if the test passes. if is looking at the return code of this function. In this case, ack gives you the return code that you need instead, so you shouldn't also be using [.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • D'oh! It's always the little things. I'll give this a check in 6 minutes when the site will allow me to – I Dabble Oct 24 '14 at 14:03
  • 1
    @eBooks_Nashville if your do this, do that are short commands you may be interested also in the alternative syntax `ack ... && do_this || do_that` – gboffi Oct 24 '14 at 14:19