Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopts not working in bash script

Tags:

bash

unix

#! bin/bash
# code for train.sh
   while getopts "f:" flag
    do
         case $flag in 
             f)
               echo "Hi" 
               STARTPOINT = $OPTARG
               ;;
         esac
    done

    echo Test range: $4
    echo Train range: $3

    #path of experiment folder and data folder:
    EXP_DIR="$1"
    DATA_DIR="$2"
    echo Experiment: $EXP_DIR
    echo DataSet: $DATA_DIR
    echo file: $STARTPOINT


I ran the command > ./train.sh test1  test2 test3 test4  -f testf  

and got the output

Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file:

So getopts option does not seem to work for some reason as you can see the nothing is printed after file and also echo "Hi" command is not executed in the case statement. Can anyone please help me with this?

like image 200
vkaul11 Avatar asked Dec 25 '22 22:12

vkaul11


1 Answers

You need to put any options before naked parameters

./train.sh -f testf test1  test2 test3 test4

with output

Hi
Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file: testf

You need a couple of changes too

while getopts "f:" flag
do
     case $flag in
         f)
           echo "Hi" 
           STARTPOINT=$OPTARG
           shift
           ;;
     esac
     shift
done

To set the environment variable and shift the got option out of the way

like image 195
KeepCalmAndCarryOn Avatar answered Jan 10 '23 08:01

KeepCalmAndCarryOn