因此,我尝试使用whiptail
命令为用户提供选择他们想要在系统中安装的不同内容的选项。我使用whiptail --checklist
如下命令:
name =$(whiptail --title "Tools to install" --checklist 20 78 4 \
"NTP" "NTP setup" OFF\
"Perl" "Perl install" OFF\
"Ruby" "Ruby install" OFF \
"Python" "Python install" OFF 3>&1 1>&2 2>&3)
现在,如果我的用户选择 Perl 和 python,这将输出“Perl”和“Python”。我正在寻找的是能够将这些输出转换为数组,因为最终我需要循环遍历这个数组。我需要将这些输出作为我正在使用的下一个命令的输入。
任何帮助或领导将不胜感激!
答案1
在一个简单的情况下,你会做这样的事情:
CHOICES=( $(whiptail --title "Tools to install" \
--checklist "Choose something" 20 78 4 \
"NTP" "NTP setup" OFF \
"Perl" "Perl install" OFF \
"Ruby" "Ruby install" OFF \
"Python" "Python install" OFF 3>&1 1>&2 2>&3) )
但是,由于返回的值whiptail
被引用,所以这不起作用。例如,这个脚本:
CHOICES=( $(whiptail --title "Tools to install" \
--checklist "Choose something" 20 78 4 \
"NTP" "NTP setup" OFF \
"Perl" "Perl install" OFF \
"Ruby" "Ruby install" OFF \
"Python" "Python install" OFF 3>&1 1>&2 2>&3) )
for choice in "${CHOICES[@]}"; do
echo "choice: $choice"
done
将输出(如果我选择 Ruby 和 Python):
choice: "Ruby"
choice: "Python"
如果你的值之一包含空格,它就会崩溃。例如,如果我像这样修改命令行:
CHOICES=( $(whiptail --title "Tools to install" \
--checklist "Choose something" 20 78 4 \
"NTP Setup" "NTP setup" OFF \
"Perl install" "Perl install" OFF \
"Ruby" "Ruby install" OFF \
"Python Install" "Python install" OFF 3>&1 1>&2 2>&3) )
for choice in "${CHOICES[@]}"; do
echo "choice: $choice"
done
我们得到:
choice: "NTP
choice: Setup"
choice: "Perl
choice: install"
您可以添加一个eval
来解决上述两个问题:
eval CHOICES=( $(whiptail --title "Tools to install" \
--checklist "Choose something" 20 78 4 \
"NTP Setup" "NTP setup" OFF \
"Perl install" "Perl install" OFF \
"Ruby" "Ruby install" OFF \
"Python Install" "Python install" OFF 3>&1 1>&2 2>&3) )
for choice in "${CHOICES[@]}"; do
echo "choice: $choice"
done
给出与前面示例相同的选择,这将输出:
choice: NTP Setup
choice: Perl install