0
while getopts abp: optchar; do
    case "${optchar}" in

    a) # an option
        export OPTION_A=1
        ;;

    b) # Yet another option
        export b=1
        ;;

    p) # An option to supply player names to the function
        IFS=',' read -r -a PLAYER_NAMES <<<"${OPTARG}"
        ;;
    esac
done

for name in "${PLAYER_NAMES[@]}"; do
    echo ${name}

Now if you supply the 'players' keyword argument with a comma separated list, the function will ignore arguments that are separated by a space. For example if you run:

bash testexp.sh -p sherman,wilson, taylor

You will get

sherman
wilson

But taylor will not be included because his name wasn't added to the array variable.

How do you make the cli parser ignore the extra space, so that output is as follows?

sherman
wilson
taylor
3
  • That's how bash works: spaces separate words. If you need the space to be part of the word, you must use quotes, or escape the space with a backslash. Commented Nov 19, 2019 at 2:38
  • 1
    Not related to the question, but I'd recommend adding a proper shebang line (#!/bin/bash or #!/usr/bin/env bash, note that it must be the first line in the script), making the script executable (chmod +x testexp.sh), and then running it directly without the bash command (./testexp.sh -p ...). Commented Nov 19, 2019 at 3:53
  • 1
    Also see How to use Shellcheck, How to debug a bash script? (U&L.SE), How to debug a bash script? (SO), How to debug bash script? (AskU), Debugging Bash scripts, etc. Commented Nov 19, 2019 at 5:44

1 Answer 1

2

Use apostrophes:

bash testexp.sh -p 'sherman,wilson, taylor'
Sign up to request clarification or add additional context in comments.

1 Comment

Double-quotes would work as well. You could also escape the space: bash testexp.sh -p sherman,wilson,\ taylor

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.