0

我正在尝试将 ps 命令的输出输出到文件,然后使用该文件来填充无线电列表。到目前为止,我遇到了问题。

eval "ps -o pid,command">/tmp/process$$
more /tmp/process$$
sed -e '1d' /tmp/process$$ > /tmp/process2$$
    while IFS= read -r pid command
    do
        msgboxlist="$msgboxlist" $($pid) $($command) "off"
    done</tmp/process2$$
    height=`wc -l "/tmp/process$$" | awk '{print $1}'`
    width=`wc --max-line-length "/tmp/process$$" | awk '{print $1}'`
    echo $height $width
    dialog \
        --title "Directory Listing" \
        --radiolist "Select process to terminate" "$msgboxlist" $(($height+7)) $(($width+4))

到目前为止,while read 不仅没有将列拆分为 2 个变量($pid是整行且$command为空白),而且当我尝试运行此脚本时,脚本正尝试将该行作为命令运行。例如:

+ read -r pid command
++ 7934 bash -x assessment.ba
assessment.ba: line 322: 7934: command not found
+ msgboxlist=
+ off
assessment.ba: line 322: off: command not found

基本上我不知道应该在哪里放置引号、双引号和反斜杠。它让我疯狂。

tl; dr将命令保存到变量中而不运行它,如何?

4

4 回答 4

1

您的脚本可以通过删除一些不必要的调用来重构,如下所示:

ps -o pid=,command= > /tmp/process$$
msgboxlist=""
while read -r pid command
do
    msgboxlist="$msgboxlist $pid $command off"
done < /tmp/process2$$

height=$(awk 'END {print NR}' "/tmp/process$$")

width=$(awk '{if (l<length($0)) l=length($0)} END{print l}' "/tmp/process$$")

dialog --title "Directory Listing" \
    --radiolist "Select process to terminate" "$msgboxlist" $(($height+7)) $(($width+4))
于 2012-03-29T15:42:24.207 回答
1

您正在尝试执行$pid$command作为命令:

msgboxlist="$msgboxlist" $($pid) $($command) "off"

尝试:

msgboxlist="$msgboxlist $pid $command off"

或使用数组:

msgboxlist=()  # do this before the while loop
msgboxlist+=($pid $command "off")

# when you need to use the whole list:
echo "${msgboxlist[@]}"
于 2012-03-29T15:33:53.197 回答
0

当您想要扩展变量时使用双引号。使用单引号禁用变量扩展。

这是一个为以后执行而保存的命令示例。

file="readme.txt"
cmd="ls $file" # $file is expanded to readme.txt
echo "$cmd" # ls readme.txt
$cmd # lists readme.txt

编辑地址阅读:

使用 read 通常会读取整行。考虑一下(经过测试):

ps o pid=,command= | while read line ; do 
  set $line
  pid=$1
  command=$2 
  echo $pid $command
done

另请注意 'ps o pid=,command=' 的不同用法以跳过显示标题。

于 2012-03-29T15:45:38.840 回答
0

我不得不承认,我不是 100% 清楚你在做什么。但我认为你想改变这一点:

        msgboxlist="$msgboxlist" $($pid) $($command) "off"

对此:

        msgboxlist+=("$pid" "$command" off)

这会将 PID、命令和“关闭”作为三个新元素添加到名为msgboxlist. 然后,您将更"$msgboxlist"改为"${msgboxlist[@]}"indialog命令,将所有这些元素作为命令的参数包含在内。

于 2012-03-29T15:30:48.113 回答