Thursday, October 6, 2022

[SOLVED] Ternary operation or default value in bash

Issue

I want to perform ternary operation in bash (?:) where if variable is null provide default value.

#!/bin/bash

while getopts l:m:ch:eh:cate:op:b flag
do
    case "${flag}" in
            l) localities=${OPTARG};;
            m) mode=${OPTARG};;
            ch) cbhost=${OPTARG};;
            eh) eshost=${OPTARG};;
            cate) category=${OPTARG};;
            op) outputDir=${OPTARG};;
            b) s3bucket=${OPTARG};;
    esac
done

out of all the variables, cbhost and eshost are optional variables. how can in bash, i can check if null then assign default value using ternary operation?? or how can assign default values to each variable which can be overridden if arguments are passed.

thanks in advance.


Solution

As per man getopt

Optstring is a string of recognized option letters (see getopt(3)); if a letter is followed by a colon, the option is expected to have an argument which may or may not be separated from it by white space.

So there are few issues:

  1. You cannot use multi letter string as option. It has to be single letter only
  2. It seems you are expecting an option value for -b option but that is not using a trailing :
  3. You can set default value of each variable in a single for loop as shown below.

Here is suggested code:

#!/bin/bash

# set default value for these variables
declare localities='loc123' mode='m123' category='cat123' \
   outputDir='op123' s3bucket='s3123' cbhost='https://cbhost:1091/'

while getopts l:m:c:e:y:d:b: flag
do
    case "${flag}" in
            l) localities=${OPTARG};;
            m) mode=${OPTARG};;
            c) cbhost=${OPTARG};;
            e) eshost=${OPTARG};;
            y) category=${OPTARG};;
            d) outputDir=${OPTARG};;
            b) s3bucket=${OPTARG};;
    esac
done

# check values of your variables
declare -p localities mode category outputDir s3bucket cbhost eshost


Answered By - anubhava
Answer Checked By - Terry (WPSolving Volunteer)