0

If a specific argument such as "-y" or "--yes" is passed I want to make the script non-interactive and skip user confirmation. I also want to know how would I pass the argument to other scripts I source.

SHORT=yq
LONG=yes,quick

PARSED=$(getopt --options $SHORT --longoptions $LONG --name "$0" -- "$@")
eval set -- "$PARSED"

q=0; autoConfirm=0

while true; do
    case "$1" in
        -q|--quick)
            q=1
            shift
            ;;
        -y|--yes)
            autoConfirm=1
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Invalid option.  Use -h for help"
            exit 3
            ;;
    esac
done

assertConfirmation () {
    local promptMsg=$1 autoConfirm=$2
    if (( autoConfirm )); then
        return
    else
        clear
        read  -n 1 -p "$promptMsg (yes/No) "
        printf '\n========================================================================'
        if [[ $REPLY =~ ^([Yy])$ ]]; then
            return
        fi
    fi
    return 1
}

if assertConfirmation "Install this?" "${autoConfirm:?}"; then
    install
fi

source installation "${autoConfirm:?}" "${q:?}"

1 Answer 1

0

It depends on what your installation script expects. To keep things simple, it is best to have it accept -y and -q as arguments. With that, you can change your case statement so that q and autoConfirm are set to -q and -y instead of 1 (and null by default), and call your installation script as:

source installation $autoConfirm $q

With that change, use [[ $autoconfirm ]] to check if it is set, instead of (( autoConfirm )).

1
  • 1
    They're setting autoConfirm to 0 at the start of the script, (( autoConfirm )) will check if it's nonzero. [[ $autoConfirm ]] would always be true, since 0 is not a null/empty string.
    – ilkkachu
    Apr 22, 2017 at 20:09

You must log in to answer this question.