5

I'm trying to test whether a file is open and then do something with the exit code. Currently doing it like this:

   FILE=/usr/local/test.sh
   lsof "$FILE" | grep -q COMMAND &>/dev/null
   completed=$? 

Is there any way you can push the exit code straight into a local variable rather than redirecting output to /dev/null and capturing the '$?' variable?

slm
  • 15,396
  • 12
  • 109
  • 124
user898465
  • 944
  • 1
  • 12
  • 23
  • 1
    what are you planning to do with the captured return code? If it's merely to drive an `if` statement then you can simply do `if lsof "$FILE" &> /dev/null; then ...` – Shawn Chin Jun 22 '12 at 10:08

1 Answers1

3

Well, you could do:

lsof "$FILE" | grep -q COMMAND; completed=$?

There's no need to redirect anything as grep -q is quiet anyways. If you want do certain action if the grep succeeds, just use && operator. Storing exit status in this case is probably unnecessary.

lsof "$FILE" | grep -q COMMAND && echo 'Command was found!'
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
tvm
  • 3,263
  • 27
  • 37