Linux – Avoid cat: no such file or directory when file does not exist

bashlinux

I am checking via a bash script whether a process is running based on the PID stored in a file. I get the error shown above when the file does not exist as the command is trying to access the file and check whether the PID is really there, so it's normal, but I would like to avoid it if possible.

Is there such a way?

The command I am using can be found below.

if kill -0 $(cat "$pid_file")

Thank you in advance.

Best Answer

[[ -f "$pid_file ]] && (cat "$pid_file" | head -n 1 | tr -d "\n")

This command will return a non-zero status. If you want an "always return zero" (sacrificing legibility):

[[ ! -f "$pid_file ]] || (cat "$pid_file" | head -n 1 | tr -d "\n")

Related Question