Skip to content
Advertisement

Bash offer numberd results for selection to user

my script takes in a site name from the user.

./run_script <site>

./run_script cambridge

Its then allows the user to checkout, edit, and commit changes to the file, via the script.

However, some sites have two to six files.

So the script lists them as follows

You have more than one Cambridge file.

Please pick from the following:

cambridge1

cambridge2

cambridge3

user enters the word cambridge[1-3]

However, I’d like to assign a value to each variable, i.e, as follows.

Please choose the option you want:

1). cambridge1

2). cambridge2

3). cambridge3

user enters 1, 2, or 3, and it picks up the file.

The current code I have is :

echo $(tput setaf 5)
echo "Please choose from the following: "
echo -n $(tput sgr0)

find path/to/file/. -name *"$site"* | awk -F "/" '{print $5}' | awk -F "SITE." '{print $2}'

echo $(tput setaf 3)

read -r input_variable
echo "You entered: $input_variable"
echo $(tput sgr0)

Advertisement

Answer

Here’s a fun way:

# save the paths and names of the options for later
paths=`find path/to/file/. -name "*$site*"`
names=`echo "$paths" | awk -F "/" '{print $5}' | awk -F "SITE." '{print $2}'`
# number the choices
n=`echo "$names" | wc -l`
[ "$n" -gt 0 ] || echo "no matches" && exit 1
choices=`paste <(seq 1 $n) <(echo "$names") | sed 's/t/). /'`

echo "Please choose from the following: "
echo "$choices"
read -r iv
echo "You entered: $iv"
# make sure they entered a valid choice
if [ ! "$iv" -gt 0 ] || [ ! "$iv" -le "$n" ]; then
    echo "invalid choice"
    exit 1
fi

# name and path of the user's choice:
name_chosen=`echo "$names" | tail -n+$iv | head -n1`
path_chosen`echo "$paths" | tail -n+$iv | head -n1`
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement