问题
I've got a bash script file that I've been working on, that I'm trying to get to be able to list the currently available Bluetooth devices and then allow the user to choose one and connect to it. I've got all of the code to work, but the listing of Bluetooth devices will not maintain the whitespace that you normally get when you run the command straight from the CLI.
In an ideal world, I would like to be able to actually list out the Bluetooth devices and have the user just select one, but I was having far too much trouble with that, so I opted for an easier solution that just lists them all and asks the user to type the mac address of the device they want to connect to.
The code that I am having trouble with is:
echo "Scanning..."
bluetoothDeviceList=$(hcitool scan | sed -e 1d)
if [ "$bluetoothDeviceList" == "" ] ; then
result="No devices were found. Ensure device is on and try again."
display_result "Connect Bluetooth Device"
else
bluetoothMacAddress=$(dialog --title "Connect Bluetooth Device" --backtitle "Pi Assist" --inputbox "$bluetoothDeviceList \n\nEnter the mac address of the device you would like to conect to:" 0 0 2>&1 1>&3);
if [ $bluetoothMacAddress != "" ] ; then
bluez-simple-agent hci0 $bluetoothMacAddress
bluez-test-device trusted $bluetoothMacAddress yes
bluez-test-input connect $bluetoothMacAddress
fi
fi
In the code I've got a display_result function, that I've shown below, just to ensure you have more of a complete look at what I'm doing.
display_result()
{
dialog --title "$1" \
--no-collapse \
--msgbox "$result" 0 0
}
回答1:
You might find something like this to be a helpful starting point. You will need to add error handling, etc
# Need a file to capture output of dialog command
result_file=$(mktemp)
trap "rm $result_file" EXIT
readarray devs < <(hcitool scan | tail -n +2 | awk '{print NR; print $0}')
dialog --menu "Select device" 20 80 15 "${devs[@]}" 2> $result_file
result=$(<$result_file)
answer={devs[$((result+1))]}
回答2:
dialog has an option to help with this (see manual):
--column-separator string
Tell dialog to split data for radio/checkboxes and menus on the occurrences of the given string, and to align the split data into columns.
One would use it for example by using sed/awk to convert the space between columns into the column separator. Doing this helps to tell dialog what parts are columns, as well as ironing out formatting problems due to the use of multibyte characters.
来源:https://stackoverflow.com/questions/30020120/how-can-i-maintain-the-whitespace-of-a-commands-results-in-a-linux-dialog-input