Bash 提供编号结果供用户选择

Bash offer numberd results for selection to user

我的脚本从用户那里获取站点名称。

./run_script <site>

./run_script cambridge

然后允许用户通过脚本检出、编辑和提交对文件的更改。

但是,有些网站有两到六个文件。

所以脚本如下列出它们

您有不止一份剑桥文件。

Please pick from the following:

cambridge1

cambridge2

cambridge3

用户输入单词 cambridge[1-3]

但是,我想给每个变量赋值,即如下。

Please choose the option you want:

1). cambridge1

2). cambridge2

3). cambridge3

用户输入 1、2 或 3,它会拾取文件。

我目前的密码是:

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

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

echo $(tput setaf 3)

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

这是一个有趣的方法:

# save the paths and names of the options for later
paths=`find path/to/file/. -name "*$site*"`
names=`echo "$paths" | awk -F "/" '{print }' | awk -F "SITE." '{print }'`
# 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`