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!
$1
in[ $1 -ge 2009 ]
, that makes it a command injection vulnerability. See also Security implications of forgetting to quote a variable in bash/POSIX shells – Stéphane Chazelas Jan 13 '23 at 07:48exists_in_list
returns an exit status, it does not echo the status, so the if statement would beif ! exists_in_list "$list_of_sectors"; then
– glenn jackman Jan 13 '23 at 13:21