以下提示應允許用戶根據輸出到陣列的填充串列進行選擇,然后列印串列及其索引,并要求用戶從串列中選擇一個數字,然后將其設定為變數。
Multiple devices detected, please select one from the list:
1. Device1
2. Device2
3. Device3
1
You have selected device Device1
下面的代碼不起作用并且有很多語法錯誤,首先我希望腳本檢測輸出是否arr=($(ip ad|awk '/state UP/ {print $2}'))包含多個條目,如果是,則運行腳本,否則設定默認值。case 陳述句不是動態的,但是,如果像下面這樣的超過 2 個案例會失敗,也許是一個回圈?
host_interfaces()
{
arr=($(ip ad|awk '/state UP/ {print $2}'))
echo "Multiple devices detected, please select one from the list:"
for i in "${!arr[@]}"; do
printf "%s%s\n" "$i. " "${arr[$i]}"
done
PS3='Please enter your choice: '
select opt in "${arr[@]}"
do
case $opt in
"1")
echo "You have selected device $opt"
export HOST_INTERFACE=$opt
;;
"2")
echo "You have selected device $opt"
export HOST_INTERFACE=$opt
;;
"Quit")
break
;;
*) echo "invalid option ;;
esac
done
}
uj5u.com熱心網友回復:
一個辦法:
#! /bin/bash
declare HOST_INTERFACE=
function host_interfaces() {
local -a arr=($(ip ad | awk '/state UP/ {gsub(/:/, "", $2); print $2}'))
if [ "${#arr[@]}" -eq 1 ]; then
HOST_INTERFACE="${arr[0]}"
return 0
fi
local opt=
HOST_INTERFACE=
echo "Multiple devices detected, please select one from the list:"
PS3='Please enter your choice: '
# Add "Quit" value to the items
select opt in "${arr[@]}" Quit; do
# "opt" does not contains the number but the associated value
case $opt in
"Quit")
#
break
;;
"")
# No value found
echo "invalid option"
;;
*)
echo "You have selected device $opt"
export HOST_INTERFACE=$opt
break
;;
esac
done
}
host_interfaces
uj5u.com熱心網友回復:
這,也許?
host_interfaces()
{
local opt='' h=''
arr=($(ip ad|awk '/state UP/ {print $2}'))
if [ "${#arr[@]}" -eq 1 ]; then
echo "One single device detected"
h="${arr[0]}"
elif [ "${#arr[@]}" -gt 1 ]; then
echo "Multiple devices detected, please select one from the list:"
PS3='Please enter your choice: '
select opt in "${arr[@]}" Quit
do
case "$opt" in
"Quit")
break
;;
"")
echo "Invalid choice"
h=''
;;
*)
echo "You have selected device $opt"
h="$opt"
;;
esac
done
else
echo "No device detected"
fi
echo "Selected device: ${h:-none}"
export HOST_INTERFACE="$h"
[ -z "$h" ] && return 1 || return 0
}
請注意,如果未找到或選擇有效設備,則該函式回傳 1,否則回傳 0。因此您可以將其用于:
if host_interfaces; then
echo "HOST_INTERFACE = $HOST_INTERFACE"
else
echo "No device selected"
fi
uj5u.com熱心網友回復:
在這里可以簡單地使用
dialog --backtitle "Device selection" --title "Multiple devices detected" --menu "please select one from the list:" 10 45 4 1 "Device1" 2 "Device2" 3 "Device3"
看 man dialog
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372609.html
上一篇:為DKIM簽名生成EML檔案
