vigri
vigri

Reputation: 477

Combine options and arguments in BASH script

My Bash-Script should accept arguments and options. Moreover arguments and options should be passed to another script.

The second part I've solved:

for argument in "$@"; do
    options $argument
done

another_script $ox $arguments

function options {
  case "$1" in
    -x) selection=1
    -y) selection=2
    -h|--help) help_message;;
    -*) ox="$ox $1";;
    *) arguments="$arguments $1";;
  esac
}

Now I don't know how to implement an argument "-t" where the user can specify some text

It should look something like this:

function options {
      case "$1" in
        -t) user_text=[ENTERED TEXT FOR OPTION T]
        -x) selection=1
        -y) selection=2
        -h|--help) help_message;;
        -*) ox="$ox $1";;
        *) arguments="$arguments $1";;
      esac
    }

Upvotes: 0

Views: 3095

Answers (3)

Huygens
Huygens

Reputation: 647

I would do the case statement inside the for loop so that I can force a shift to the second next argument. Something like:

while true
do
  case "$1" in
    -t) shift; user_text="$1";;
    -x) selection=1;;
...
  esac
  shift
done

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74108

You can use getopts for this

while getopts :t:xyh opt; do
    case "$opt" in
    t) user_text=$OPTARG ;;
    x) selection=1 ;;
    y) selection=2 ;;
    h) help_message ;;
    \?) commands="$commands $OPTARG" ;;
    esac
done

shift $((OPTIND - 1))

The remaining arguments are in "$@"

Upvotes: 3

chepner
chepner

Reputation: 532418

Your problem is that when options can take arguments, it isn't sufficient to process the arguments word-by-word; you need more context than you are providing the options function. Put the loop inside options, something like this:

function options {
    while (( $# > 0 )); do
        case "$1" in
            -t) user_text=$2; shift; ;;
            -x) selection=1 ;;
            # ...
        esac
        shift
    done
}

Then call options on the entire argument list:

options "$@"

You may also want to take a look at the getopts built-in command or the getopt program.

Upvotes: 2

Related Questions