Linux

從whiptail 命令的輸出創建一個數組

  • July 12, 2022

所以,我試圖使用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”。我正在尋找的是能夠將這些輸出轉換成一個數組,因為最終我需要遍歷這個數組。我需要將這些輸出作為輸入提供給我正在使用的下一個命令。

任何幫助或領導將不勝感激!

在一個簡單的情況下,你會做這樣的事情:

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

引用自:https://unix.stackexchange.com/questions/709589