4

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:

#!/bin/ksh

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.

N West
  • 143

1 Answers1

5

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.

So:

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

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"
  • 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