0

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
    }

3 Answers 3

3

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 "$@"

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.