I wrote a shell script to start a program ${programName}.

This program happens to creates temporary work files in a folder, <workFolderLocation>/SAS_work<randomHex>00<pidHex>_<server>, in which pidHex is the hexadecimal representation of the PID of the program. Usually this temporary folder disappears when the program finishes.

That program also creates a log file, which I name ${logFolder}/${programName}_$$.log, so it has the PID of the Shell script.

Unfortunately, these pid's are not identical, so if a program does not clean up its work folder, I have no easy way to find the log corresponding to the work folder.

(I used to solve this by looking into the log file for the pid with awk and rename the log file in the script, but unfortunately, the logs are changed and don't contain the pid anymore.)

Edit in response to Stéphane Chazelas

In the real situation, the log is the standard output of the program. The log name is one of the parameters.

Further, if the program ends with a returncode 1, the script should end with a retunrcode 0, so as not to log an error in our job scheduling system.

Therefore the script currently looks more like:

programName=<some calculation>
otherArguments=<other calculation>

"${programName}" -log "$logFolder/${programName}_$$.log" "${otherArguments}"
if [ $rc -eq 1 ]; then
        exit 0
        exit $rc

Can I still handle the return code after this?

exec "${programName}" -log "$logFolder/${programName}_$$.log" "${otherArguments}"

1 Answer 1


If you run

exec "$programName" > "$logFolder/${programName}_$$.log" 2>&1

then the program will be executed in the same $$ process.

That obviously will be the last thing your shell script will do.

If the script needs to do other things afterwards, you can start a new sh process that does the redirection and executes the program in the same process:

LOGPREFIX="$logFolder/$programName" sh -c '
  exec "$0" "$@" > "${LOGPREFIX}_$$.log" 2>&1
  ' "$progName" and some extra arguments if needed

printf>&2 '%s\n' "$progName terminated with $? exit status"


Or if the rest of the script needs to do something with the pid of the program:

LOGPREFIX=$logFolder/$programName sh -c '
  exec "$0" "$@" > "${LOGPREFIX}_$$.log" 2>&1
  ' "$progName" and some args if needed &

printf>&2 '%s\n' "$progName was started asynchronously with pid $pid"
wait "$pid"
printf>&2 '%s\n' "$progName terminated with exit status $exit_status"

Beware that in most shells, starting a command asynchronously has the side effect of redirecting its stdin to /dev/null.

  • Unfortunately, I still need to do something after running the program. See my edit to the question . I will elaborate and test this in the real situation next week. Nov 21, 2023 at 20:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .