0

I'm writing a bash script that has optional flags but also an input.

I can't get the input as $1 because when flags are present the input is shifted.

So for example if I run script.sh test then $1 will be equal to test.

But if I run script.sh -b test then $1 will be equal to -b.

while getopts 'bh' flag; do
  case "${flag}" in
    b) boxes= 'true' ;;
    h) echo "options:"
       echo "-h, --help                show brief help"
       echo '-b                        add black boxes for monjaro'
       ;;
    *) error "Unexpected option ${flag}" ;;
  esac
done

echo $1;

The amount of flags I have is not set, I know I will add more in the future.

How can I consistently get the first non-flag value?

  • So, what is your question ? – Carpette Mar 27 '17 at 12:56
  • @Carpette added to end of question. How can I get first non-flag value, given unknown amount of flags – Philip Kirkbride Mar 27 '17 at 12:58
4

You typically use getopts as:

while getopts...; do
  # process options
  ...
done
shift "$((OPTIND - 1))"

printf 'First non-option argument: "%s"\n' "$1"

The shift above discards all option arguments (including the trailing -- if any) processed by getopts.

  • works great thanks, will accept in 10 – Philip Kirkbride Mar 27 '17 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.