I want to use my shell script like this:
myscript.sh -key keyValue
How can I get the keyValue ?
I tried getopts, but it requires the key to be a single letter!
I want to use my shell script like this:
myscript.sh -key keyValue
How can I get the keyValue ?
I tried getopts, but it requires the key to be a single letter!
 
    
    use a manual loop such as:
while :; do
  case $1 in
    -key)
      shift
      echo $1
      break
    ;;
    *)
      break
  esac  
done
 
    
    No need to use getopts:
while [ "$#" -gt 0 ]; do
    case "$1" in
    -key)
        case "$2" in
        [A-Za-z])
            ;;
        *)
            echo "Argument to $1 must be a single letter."
            exit 1
            ;;
        esac
        keyValue=$2
        shift
        ;;
    *)
        echo "Invalid argument: $1"
        exit 1
        ;;
    esac
    shift
done
If your shell is bash it could be simplified like this:
while [[ $# -gt 0 ]]; do
    case "$1" in
    -key)
        if [[ $2 != [A-Za-z] ]]; then
            echo "Argument to $1 must be a single letter."
            exit 1
        fi
        keyValue=$2
        shift
        ;;
    *)
        echo "Invalid argument: $1"
        exit 1
        ;;
    esac
    shift
done
 
    
    I really think it's well worth learning getopts: you'll save lots of time in the long run.
If you use getopts then it requires short versions of switches to be a single letter, and prefixed by a single "-"; long versions can be any length, and are prefixed by "--". So you can get exactly what you want using getopts, as long as you're happy with
myscript.sh --key keyValue
This is useful behaviour for getopts to insist on, because it means you can join lots of switches together. If "-" indicates a short single letter switch, then "-key" means the same as "-k -e -y", which is a useful shorthand.
