1

I have a script which basically parses a file. While executing this script i want to set two flags.

These are my two cases: I want to set --hello-you as a flag which then takes two mandatory arguments after it: ./script.sh --hello-you <FILE> <PATH>

I want -h or --help to provide help manual. ./script.sh --help or ./script.sh -h I know that -h or --help is easy by casing $1 but the problem is that when user preses --hello-you the program recognizes same as -h

1
1

It would probably be best to forget about long-options and simply use getopts to do this but otherwise you can loop through your positional parameters similar to:

#!/bin/bash

usage () {
    cat <<EOF >&2
    Usage: $(basename "$0") [-h] --hello-you FILE PATH
EOF
    exit 1
}

while (($#)); do 
    case $1 in
        --hello-you)
            file=$2
            path=$3
            shift 2
            [[ -z "$file" || -z "$path" ]] && usage
        ;;
        -h|--help)  usage;;
        *)          usage;;
    esac
    shift
done

echo "File is $file"
echo "Path is $path"

I'm not sure what you tried before but case won't interpret --hello-you as -h. Maybe your case had something like --h*)?

Additionally this is only checking that file and path are set and not that they are files but you may want to do that depending on whether or not you expect them to exist before the script is run. It also doesn't require --hello-you be set at all because it isn't clear if that was your intent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.