Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In ksh88, I can source a file using the "dot" command, like

. /my/file/source.ksh

However, if source.ksh doesn't exist, I want to trap the error.

So I tried this:


trap "echo 'Source Not Found'; exit 1" ERR
. test2.ksh

But the trap never displays the error message, the script returns with:

./test.ksh[4]: test2.ksh:  not found.

I even tried just using trap without any signals and it still doesn't catch the error.

Is there any way to catch this error? I must use ksh88 for this script. Bash answers are useless for this question.

I am aware that I can test for the existence of the file beforehand, I was just hoping there would be a way to trap this error without having to do that, as there are a bunch of these includes in my script.

share|improve this question
up vote 4 down vote accepted

You can use the command command to remove the special behavior (whereby failure causes the shell to exit among other things) of special builtins in POSIX shells like ksh or bash.


if ! command . /my/file/source.ksh; then
  echo >&2 ". failed"
  exit 1

Now, . may fail if /my/file/source.ksh can't be found, or can't be open for reading, or there's an error reading it or parsing it, or the last command run within it returns failure.

If you only want to consider the case where source.ksh can't be open for reading, you can use exec (another special builtin):

die() {
  IFS=" "
  printf >&2 'Error: %s\n' "$*"
  exit 1
command exec 3< /my/file/source.ksh || die "Can't read the file"
command . /dev/fd/3

Or use eval instead of .:

code=$(cat /my/file/source.ksh) || die "Can't read the file"
eval "$code"
share|improve this answer
Thanks! I really want the case where it fails for any reason - the files just contain function definitions. I'll try out the command command and see how it goes. – N West Apr 18 '13 at 20:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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