1

I have PID file and I want to get PID number so this is what I am doing.

[root@linux ~]# PID=`cat /usr/local/foo/var/run/foo.pid`
[root@linux ~]# echo $PID
3414

sometimes this file doesn't existing and this throwing file error, I want to specify to not throw an error, if file doesn't exist.

[root@linux ~]# PID=`cat /usr/local/foo/var/run/foo.pid`
cat: /usr/local/foo/var/run/foo.pid: No such file or directory

I am trying to use 2&> /dev/null but it's not working, what am I doing wrong?

  • 1
    PID=$(cat /usr/local/foo/var/run/foo.pid 2>/dev/null) – cuonglm Mar 4 '16 at 17:12
  • Quicky put your command in ANSWER i would like to give you +1 Vote... it works!!! – Satish Mar 4 '16 at 17:13
  • 1
    @cuonglm answer him dammit! :) – Otheus Mar 4 '16 at 17:16
4

First of all, start using $() for command substitution instead of older, problematic ``.

In you case, cat is showing error message when the file does not exist on the STDERR stream (file descriptor 2).

With command susbstution you are only saving what is on the STDOUT to the variable PID. So to get rid of the error message when the file does not exist, redirect the file descriptor 2 to /dev/null:

PID=$(cat /usr/local/foo/var/run/foo.pid 2>/dev/null)

In zsh and ksh derivatives, you can use shortcut for cat:

PID=$(< /usr/local/foo/var/run/foo.pid 2>/dev/null)

In bash, you can use a=$(<file) but not a=$(<file 2>/dev/null).

1

In general, you can check that a file exists before trying to read it by using the test aka [ command:

if [ -f /usr/local/foo/var/run/foo.pid ]; then
    PID=$(cat /usr/local/foo/var/run/foo.pid)
fi

or if you prefer one-liners:

[ -f /usr/local/foo/var/run/foo.pid ] && PID=$(cat /usr/local/foo/var/run/foo.pid)

In a POSIX shell, using the -f option will return

True if pathname resolves to an existing directory entry for a regular file. False if pathname cannot be resolved, or if pathname resolves to an existing directory entry for a file that is not a regular file.

The -r test might be more appropriate as it also checks that the shell user actually has permission to read the file.

  • More complex way but still works for problem – rɑːdʒɑ Mar 5 '16 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.