0

I am trying to run the scripts as below. I want to set the flags to true but it doesnt work.

./test.sh ./api_service -s -i

if I run the scripts only with flags i am able to get the expected output. how to pass arguments and flags to the script?

./test.sh -s -i

script:

#!/bin/bash

input_project_path="$1"
name=$(echo ${input_project_path} | cut -d"/" -f2)
echo $name

skiptests=false
install_libs=false

while getopts ":si" option; do
  case "${option}" in
    s )
        skiptests=true
        if [ "$skiptests" = true ] ; then
            echo "something....";
        else
            echo "test...";
        fi
        ;;
    i)
        install_libs=true
        ;;
    \?)
        echo "Invalid option: -$OPTARG" >&2
        exit 1
        ;;
    :)
        echo "Option -$OPTARG requires an argument." >&2
        exit 1
        ;;
    esac
done

echo $skiptests
echo $install_libs
nad87563
  • 3,672
  • 7
  • 32
  • 54

1 Answers1

0

If you need to set a value for a flag, then you need to make 2 changes:

  • add : after the flag option in the getopts string
  • Save the value using $OPTARG

For example, if you want to pass a value for flag i, but not s you'd do something like this:

while getopts ":si:" option; do
  case "${option}" in
    s )
        skiptests=true
        if [ "$skiptests" = true ] ; then
            echo "something....";
        else
            echo "test...";
        fi
        ;;
    i)
        install_libs=$OPTARG
        ;;
    ...
    esac
done

I used ... to avoid copying the rest of your case statement.

Notice that:

  • There is an extra : after the i option
  • And in the i's case statement, the value is set to $OPTARG's value.
  • There was no change made to the s case
  • Also note the options' values come after the corresponding flags

See this thread An example of how to use getopts in bash for a more in depth explanation of getopt.

alamoot
  • 1,966
  • 7
  • 30
  • 50