我想制作一个带有对话框的程序来显示我的计算机体系结构。但我有一些错误的输出。这是我的脚本:
#!/bin/bash
# ComputerArchitecture_interactive_dialog: an interactive dialog to see the ComputerArchitecture in a simple way.
DIALOG_CANCEL=1
DIALOG_ESC=255
HEIGHT=0
WIDTH=0
display_result() {
dialog --title "$1" \
--no-collapse \
--msgbox "$result" 0 0
}
while true; do
exec 3>&1
selection=$(dialog \
--backtitle "Computer Architecture list" \
--title "ComputerArchitectuur" \
--clear \
--cancel-label "Exit" \
--menu "Use [ENTER] to select:" $HEIGHT $WIDTH 4 \
"1" "Information about Processors and Cores" \
"2" "Information about RAM-memory" \
"3" "Information about connected drives and USB-devices" \
"4" "Inforamtion about the current load" \
2>&1 1>&3)
exit_status=$?
exec 3>&-
case $exit_status in
$DIALOG_CANCEL)
clear
echo "Program stopped."
exit
;;
$DIALOG_ESC)
clear
echo "Program closed." >&2
exit 1
;;
esac
case $selection in
0 )
clear
echo "Program stopped."
;;
1 )
result=$(echo "Processors and Cores"; lscpu)
display_result "Processors and Cores"
;;
2 )
result=$(echo "RAM"; dmicode --type 17)
display_result "RAM"
;;
3 )
result=$(echo "Connected drives and USB-devices";lsblk \lsusb)
display_result "Connected drives and USB-devices"
;;
4 )
result=$(echo "Current load"; top)
display_result "Current load"
;;
esac
done
这是错误的输出:
Error: Expected 2 arguments, found only 1.
Use --help to list options.
答案1
您需要对流程替换进行双引号。他们全部。使用变量时还需要用双引号引起来(同样,所有变量 - $selection、$HEIGHT、$WIDTH、$DIALOG_CANCEL、$DIALOG_ESC 以及您使用的任何其他变量)。
例如,不要这样做:
result=$(echo "Processors and Cores"; lscpu)
做这个:
result="$(echo "Processors and Cores"; lscpu)"
并且不要这样做:
case $selection in
做这个:
case "$selection" in
更好的是,重写您的display_result
函数,使其不依赖于全局变量 ( $result
)。
例如:
display_result() {
# This version of display_result takes multiple args.
# The first is the title. The rest are displayed in the
# message box, with a newline between each arg.
# To insert a blank line use an empty string '' between any two args.
title="$1" ; shift
dialog --title "$title" \
--no-collapse \
--msgbox "$(printf "%s\n" "$@")" 0 0
}
然后,在您的 case 语句中,您将像这样使用它:
...
case "$selection" in
1) display_result 'Processors and Cores' "$(lscpu)" ;;
2) display_result 'RAM' "$(dmicode --type 17)" ;;
...
esac