1

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?

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

1 Answer 1

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.

1
  • works great thanks, will accept in 10 Commented Mar 27, 2017 at 12:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .