Search code examples
linuxbashlsof

Redirect lsof exit code into variable


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?


Solution

  • 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!'