bashksh

Conditionally bypass a command based on type of shell bash vs ksh


I have this line in script.

if [ "$(ps -p $$ -o comm=)" = "bash" ]; then
    exec 1> >(tee -ia $SDIR/bash.log)
fi

It only works in bash, but when the shell is not bash, that is in ksh, I get this error

./col[2]: 0403-057 Syntax error at line 3 : `>' is not expected.

Any way to make the script generic? I want basically to create a output log file of the script if it runs in bash/ksh and also display on screen.

Tried

if [ "$(ps -p $$ -o comm=)" = "bash" ]; then
    exec 1> >(tee -ia $SDIR/bash.log)
fi

but does not work.


Solution

  • Any way to make the script generic?

    You can get output to both screen and log in both shells, which I guess is even more generic than you asked. Use a compound command ({ ... }) to wrap everything whose output you want to capture in the log, and pipe its output into tee.

    Be aware that the use of a pipe will force the compound command into a subshell, which is not analogous to your version. That could conceivably have unwanted side effects, but I'm inclined to guess that that's unlikely in your particular case.

    Example:

    SDIR=/foo/bar
    
    {
        echo 'Hello, World!'
    } | tee -ia "${SDIR}/bash.log"