如何在sh脚本中正确使用dialog命令?

How to use right the dialog command in the sh script?

我写了一些脚本:

#!/bin/sh

dialog --menu \
"Please select a partition from the following list to use for your \
root (/) Linux partition." 13 70 3 \
"/dev/hda2" "Linux native 30724312K" "/dev/hda4" "Linux native 506047K"


DISKS='"disk1" "50 Gb" "disk2" "100 Gb"'

dialog --menu \
"Please select a partition from the following list to use for your \
root (/) Linux partition." 13 70 3 \
$DISKS

第一个电话看起来不错。

第二个电话看起来很糟糕。

我需要通过变量传递有关驱动器的信息。请告诉我为什么第二个版本的调用没有按预期工作?

我们问一下shellcheck:

$ shellcheck myscript

In myscript line 9:
DISKS='"disk1" "50 Gb" "disk2" "100 Gb"'
      ^-- SC2089: Quotes/backslashes will be treated literally. Use an array.


In myscript line 14:
$DISKS
^-- SC2090: Quotes/backslashes in this variable will not be respected.

detailed error page给出解释:


Bash does not interpret data as code. Consider almost any other languages, such as Python:

print 1+1   # prints 2
a="1+1"
print a     # prints 1+1, not 2

Here, 1+1 is Python syntax for adding numbers. However, passing a literal string containing this expression does not cause Python to interpret it, see the + and produce the calculated result.

Similarly, "My File.txt" is Bash syntax for a single word with a space in it. However, passing a literal string containing this expression does not cause Bash to interpret it, see the quotes and produce the tokenized result.

The solution is to use an array instead, whenever possible.


好的,让我们试试看:

#!/bin/bash
DISKS=("disk1" "50 Gb" "disk2" "100 Gb")

dialog --menu \
"Please select a partition from the following list to use for your \
root (/) Linux partition." 13 70 3 \
"${DISKS[@]}"

这有效。

但是,这是一个 bash 特定的解决方案。如果您希望它适用于 sh,在这种情况下,您可以通过设置内部字段分隔符来选择空格以外的分隔符:

#!/bin/sh
IFS=":" # Split on colons
set -f  # Prevent globbing
DISKS='disk1:50 Gb:disk2:100 Gb'
dialog --menu \
"Please select a partition from the following list to use for your \
root (/) Linux partition." 13 70 3 \
$DISKS

这也按预期工作。如果您的脚本比这个长,您需要将 IFS 设置回其原始值。