I am trying to create a bash script to create json files from a txt file in AWS. The script below is failing (I think) at the first case
option. I think it's because I have the $opt
variable which is a catch all. Basically I want it to exit if you input the exit number. Create the files for any other valid number, and with an invalid number, ask you for another option.
#!/bin/bash
clear
# define variables
NOW=$(date +%F-%a-%H.%M) # year-month-date-day-hour.minute format
# display region list menu
region=($(aws ec2 describe-regions | jq -r '.Regions[].RegionName'))
aws ec2 describe-security-groups --region $region | jq -r '.SecurityGroups[].GroupId' > $region.txt
PS3="Select Region number: "
select opt in "${region[@]}" "exit"
do
case $opt in
$opt)
aws ec2 describe-security-groups --region $region | jq -r '.SecurityGroups[].GroupId' > $region.txt
# read security groups file into array and create individual json files
mkdir -p "$region"
while read group; do
echo "Processing group: $group"
aws ec2 describe-security-groups --region $region --group-ids "$group" > "$region"/"$group-"$DATE".json"
done < $region.txt
break
;;
"exit")
echo "Exiting..."
exit
;;
*)
echo "Invalid option, try again..."
esac
done
# cleanup security group text file
rm $region.txt
The expected behaviour is that you enter a number from 1-14 and Security Group json files are created into a directory of the region name. This part works. However if you enter 15 to exit this happens;
Select Region number: 15
Processing group: sg-4fec0526
Also if you enter an incorrect number e.g. 16 the same things happens as with 15;
Select Region number: 16
Processing group: sg-4fec0526
Numer 15 should exit and anything not 1-15 should echo out Invalid... and ask you to enter another number.
As for why it's a menu? I want granular control just now
aws
command you are parsing. Also, as a general rule, why in the world would you make this so hard to use? Why use menus and force your user to type stuff (which is impractical, error prone and means your script can't be automated) instead of passing all options at run time as arguments?aws ec2 describe-regions | jq -r '.Regions[].RegionName'
. You are parsing whatever that command returns so we can't test a working solution for you if you don't show us what you are parsing.$opt
to itself, so that will always be true, but we can give you a solution as well as pointing out the error if you give us enough information. For instance, if that command returns strings, why are you expecting to select numbers?