Home > Software design >  Argument is empty using getopts
Argument is empty using getopts

Time:03-30

I want to be able to run a script like run.sh test -a but my arguments are empty.

#!/bin/bash

function install() {
    echo "Installing $1"
}

while getopts "ab" ARG; do
  case "$ARG" in
    a) install
       echo "Setting up A" ;;
    b) install
       echo "Setting up B" ;;
    *​) echo "argument missing" ;;
  esac
done

My expected output would be if I run run.sh test -a:

Installing test
Setting up A

However there is no output returned. If I run run.sh -a, I get:

Installing
Setting up A

CodePudding user response:

Probably not the most elegant way but I got it sort of working by using the second argument instead.

Ended up reworking it like so:

install=$2

function install() {
    echo "Installing $install"
}

while getopts "ab" ARG; do
  case "$ARG" in
    a) install
       echo "Setting up A" ;;
    b) install
       echo "Setting up B" ;;
    *​) echo "argument missing" ;;
  esac
done

So I running run.sh -a test would return:

Installing test
Setting up A

CodePudding user response:

getopts does not allow you to specify the options after the non-option arguments. This is a general principle of many Unix tools, though some have deviated.

  • Related