Issue
I've written a script to list all local branches in my repository.
#!/bin/bash
clear
branches=()
menuposition=0
eval "$(git for-each-ref --shell --format='branches+=(%(refname))' refs/heads/)"
for branch in "${branches[@]}"; do
menuposition=$((menuposition+1))
echo "$menuposition) $branch"
done
The output is ...
1) master
2) foo
3) bar
I can use read command to get user input. But, ... How can I, then, checkout the branch choosed by user?
Solution
#!/bin/bash
clear
options=('Exit')
#for bash version 4 or higher use mapfile.
#Fallback to while loop if mapfile not found
mapfile -t options < <(git for-each-ref \
--format='%(refname:short)' refs/heads/) &>/dev/null \
|| while read line; do options+=( "$line" ); done \
< <(git for-each-ref --format='%(refname:short)' refs/heads/)
select opt in "${options[@]}"
do
if [[ "$opt" ]] && [[ "$opt" == 'Exit' ]]; then
echo "Bye Bye"
break
elif [[ "$opt" ]]; then
git checkout "$opt"
break
else
echo "Wrong Input. Please enter the correct input."
fi
done
Answered By - pratZ Answer Checked By - Terry (WPSolving Volunteer)