Search code examples
linuxbashshellsolarisfreebsd

bash script porting issue related to script program


I am trying to port an existing bash script to Solaris and FreeBSD. It works fine on Fedora and Ubuntu.

This bash script uses the following set of commands to flush the output to the temporary file.

    file=$(mktemp)
    # record test_program output into a temp file
    script -qfc "test_program arg1" "$file" </dev/null &

The script program does not have -qfc options on FreeBSD and Solaris. On Solaris and FreeBSD, script program only has -a option. I have done the following until now:

1) update to latest version of bash. This did not help.

2) Try to find out where exactly is the source code of "script" program is. I could not find it either.

Can somebody help me out here?


Solution

  • script is a standalone program, not part of the shell, and as you noticed, only the -a flag is available in all variants. The FreeBSD version supports something similar to -f (-F <file>) and doesn't need -c.

    Here's an ugly but more portable solution:

    buildsh() {
        cat <<-!
            #!/bin/sh
            SHELL="$SHELL" exec \\
        !
        # Build quoted argument list
        while [ $# != 0 ]; do echo "$1"; shift; done |
        sed  's/'\''/'\'\\\\\'\''/g;s/^/'\''/;s/$/'\''/;!$s/$/ \\/'
    }
    
    # Build a shell script with the arguments and run it within `script`
    record() {
        local F t="$(mktemp)" f="$1"
        shift
        case "$(uname -s)" in
            Linux) F=-f ;;
            FreeBSD) F=-F ;;
        esac
        buildsh "$@" > "$t" &&
        chmod 500 "$t" &&
        SHELL="$t" script $F "$f" /dev/null
        rm -f "$t"
        sed -i '1d;$d' "$f" # Emulate -q
    }
    
    file=$(mktemp)
    # record test_program output into a temp file
    record "$file" test_program arg1 </dev/null &