0

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!

Kevin
  • 300
  • 1
  • 12

3 Answers3

0

use a manual loop such as:

while :; do
  case $1 in
    -key)
      shift
      echo $1
      break
    ;;
    *)
      break
  esac  
done
Farvardin
  • 5,336
  • 5
  • 33
  • 54
0

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
konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

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.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67