1

I have a bash script myscript.sh. I mean to call another script, command or builtin from within it, e.g., diff. I mean to pass options to myscript.sh, some of which would be passed to diff when calling it.

The way I implemented this is by setting up an option string optstring via getopt, and then using

eval "diff ${optstring} ${file} ${TRG_DIR}/${filebase2}"

So far, it worked, but I do not know if this is prone to issues when passing arguments with wildcards, etc. At any rate, ...

Is there a better way to do it?


The way I set up optstring is
set -o errexit -o noclobber -o nounset -o pipefail
params="$(getopt -o qy --long brief,side-by-side,suppress-common-lines --name "$0" -- "$@")"

if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi

echo params=$params
echo params=$@

eval set -- "$params"

optstring=""
# These variables are likely not needed
brief=false
sbs=false
scl=false

#while false ; do
while true ; do
    case "$1" in
        -q|--brief)
            optstring=${optstring}" -q"
            brief=true
            echo "brief"
            shift
            ;;
        -y|--side-by-side)
            optstring=${optstring}" -y"
            sbs=true
            echo "side-by-side"
            shift
            ;;
        --suppress-common-lines)
            optstring=${optstring}" --suppress-common-lines"
            scl=true
            echo "suppress-common-lines"
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Not implemented: $1" >&2
            exit 1
            ;;
    esac
done
echo optstring=${optstring}
miken32
  • 42,008
  • 16
  • 111
  • 154

1 Answers1

2

Use an array. Arrays can handle multi-word arguments with whitespace. Initialize a blank array with:

options=()

To append an option, do:

options+=(--suppress-common-lines)

Then finally you can get rid of the eval when you call diff and just call it normally. Make sure to quote all of the variable expansions in case they have whitespace:

diff "${options[@]}" "$file" "$TRG_DIR/$filebase2"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578