Search code examples
bashgetopts

How to make an argument optional in getopts bash?


I would like to make one of the optional characters (-t) which should not accept any argument in getopts bash. This is where i got so far

while getopts ":hb:q:o:v:t" opt; do
  case $opt in
    b)
     Blasting_list=$OPTARG
     ;;
    l)
    query_lincRNA=$OPTARG 
     ;;
    q)
    query_species=$OPTARG 
     ;;
    o)
     output=$OPTARG # Output file
     ;;  
    t)
     species_tree=$OPTARG
     ;;
    h)
    usage  
     exit 1
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

I want to run the above script like this..

bash test.sh -b Blasting_list.txt -l Sample_query.fasta -q Atha -o test_out -v 1e-20 -t

Then it should execute the below loop

(-----)
if [ ! -z $species_tree ]; 
then 
  mkdir -p ../RAxML_families
  perl /Batch_RAxML.pl aligned_list.txt
  rm aligned_list.txt
else
  rm aligned_list.txt
fi
(-----)

And if i run like this, it should skip the loop.

bash test.sh -b Blasting_list.txt -l Sample_query.fasta -q Atha -o test_out -v 1e-20
(-----)
(-----)

I tried to play with getopts options but i cannot make it work.


Solution

  • probably the easiest way is to set species_tree to true iff there's the -t command line flag:

    species_tree=false                       # <-- addition here
    
    while getopts ":hb:q:o:v:t" opt; do
      case $opt in
    ...
        t)
          species_tree=true                  # <-- change here
          ;;
    ...
      esac
    done
    
    if $species_tree; then                   # <-- change here
    ...