1

I have this line in my script:

#Search process id files 
PID_FILE=$(ls $PROFILES_PATH*/*/*/*.pid )

When the ls command doesn't find any file it shows the following output:

ls: *.pid: No such file or directory

Is there any way to capture that error and show a custom error message instead?

0

2 Answers 2

4

You can redirect stderr of the command to /dev/null, then print your own error message after checking the exit status:

PID_FILE=$(ls $PROFILES_PATH*/*/*/*.pid 2>/dev/null)
[ $? != 0 ] && echo "Couldn't find PID."

In general I'd advise against using ls for this, though. You should probably use something like find $PROFILES_PATH -iname '*.pid' instead.

Sign up to request clarification or add additional context in comments.

4 Comments

Please, don't support useless use of ls.
I think giving a quick solution and a preferrable alternative is better than running away horrified, at least some of the time. In this case, for example, perhaps the OP will learn about stderr redirection and $? even when his/her use of ls is wrong.
True. find isn't the easier alternative though. A simple test is almost enough.
Hi, thanks for your answer. I used the find command before using the ls but the time of execution was too long, that's why I used ls instead.
2

The ls is totally superfluous. The shell looks up the file when expanding the pattern, so all we need to do is:

  • check whether the pattern matched anything
  • check/get rid of any additional matches if there is more than one (not taken care of in the question either, but it's another potential problem).

The first part is trivial using test or it's [ alias. Unfortunately the second is slightly non-trivial, because printf "%s" pattern alone does not work, so one has to resort to a helper function that simply outputs it's first argument.

The solution is to write a short helper shell function like this:

first() { printf "%s" "$1"; }
PID_FILE=$(first $PROFILES_PATH*/*/*/*.pid)
[ -f "$PID_FILE" ] || echo "Couldn't find PID."

In this case the PID_FILE will be equal to pattern if it's not found and the -f test will tell you whether it matched. Alternatively you can move the test into the helper function:

matches() { [ -f "$1" ] && printf "%s" "$1"; }
PID_FILE=$(matches $PROFILES_PATH*/*/*/*.pid)
[ $? != 0 ] && echo "Couldn't find PID."

This way you still get empty PID_FILE and non-zero exit status if the file is not found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.