Home > other >  Using bash, check to see if the entered value is in a list
Using bash, check to see if the entered value is in a list

Time:01-13

I'm not familiar with bash scripting. In bash script, I'm attempting to validate a prompted value against a defined list, so that when I call:

./test.bash [caseyear] [sector]

caseyear and sector will be validated in the following attempted bash script:

Validating Year
#1 Check the value of the caseyear Parameter
if [ "$1" -eq "$1" 2> /dev/null ]; then
  if [ $1 -ge 2009 ]; then
    export caseyear=$1
  else
    echo -e "\n\tSpecify [caseyear] value greater than or equal to 2009.\n"
    exit 4
  fi
else
  echo -e "\n\tSpecify [caseyear] value greater than or equal to 2009.\n"
  exit 3
fi

I'm having trouble validating that the entered value must be in the sector list, so I tried the following script:

Validating Sector

#sector list
list_of_sectors="11 40 44_45 52 10_11"

#1 Check if sector value is in the sector list
$ function exists_in_list() {
    LIST=$1
    DELIMITER=$2
    VALUE=$3
    LIST_WHITESPACES=`echo $LIST | tr "$DELIMITER" " "`
    for x in $LIST_WHITESPACES; do
        if [ "$x" = "$VALUE" ]; then
            return 0
        fi
    done
    return 1
}

#2 Check if sector is null
if [ -z "$2" ]; then
    echo -e "\n\tSpecify [caseyear] sector value.\n"
    exit 2
else
  #export omitflag="$(echo $2 | tr '[a-z]' '[A-Z]')" #Convert to upper case
#3 Check if sector value is in the sector list
  export sector

#------------------->Problem Area
#How do I pass the entered $sector value to exists_in_list function that matches with the list, $list_of_sectors?

  if [ $(exists_in_list $list_of_sectors) -ne 0 ] ; then
    echo -e "\n\tSpecify [sector] sector value.\n"
    exit 1
  fi
fi

echo -e "\nYou Specified - CaseYear:$caseyear, Sector:$sector"

Thank you!

CodePudding user response:

Here's a concise way to portably test if a word appears in a string containing space separated words:

list_of_sectors="11 40 44_45 52 10_11"
sector="11"
case " $list_of_sectors " in
  (*" $sector "*) echo yes;;
  (*)             echo no;;
esac

No loops, no pipes, pure POSIX shell. Neat.

CodePudding user response:

Use an array

#sector list
list_of_sectors=( 11 40 44_45 52 10_11 )

#1 Check if sector value is in the sector list
function exists_in_list() {
    local value="$1" 
    for s in "${list_of_sectors[@]}"; do
        if [[ "$s" == "${value}" ]]; then
            return 0
        fi
    done
    return 1
}

if exists_in_list "$sector"; then
    ...
fi
  • Related