2012-03-29 29 views
0

我想获得输出到ps命令输出到一个文件,然后使用该文件来填充radiolist。到目前为止,我遇到了问题。保存命令到一个变量,而不是运行它

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)) 

到目前为止,不仅在同时读不列分成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将命令保存到变量中而不运行它,怎么样?

+2

[请](http://mywiki.wooledge.org/BashFAQ/048)[考虑](http://mywiki.wooledge.org/ProcessManagement)你在做什么(http:// www .grymoire.com/Unix的/ Quote.html)。该代码是可怕的!您可能想在[代码评论](http://codereview.stackexchange.com/)上发帖。 – l0b0 2012-03-29 15:30:34

回答

0

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

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

这样:

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

这将增加的PID,命令,和“关”三个新元素命名msgboxlist阵列。然后,您将在dialog命令中将"$msgboxlist"更改为"${msgboxlist[@]}",以将所有这些元素包含为该命令的参数。

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[@]}" 
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)) 
+0

不错的重构。我现在可以真正理解这个意图。:-)另外,'width ='行可以缩短一点点:'awk'length($ 0)> l {l = length($ 0)} END {print l}'' – ghoti 2012-03-29 15:56:35

0

当您希望展开变量时使用双引号。使用单引号禁用变量扩展。

下面是为以后执行保存的命令示例。

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

编辑adressing读:

使用读通常读取整行。考虑这个代替(测试):

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

还要注意的不同的使用“PSÔPID =,命令=”跳过显示标题。

+1

不需要'eval $ cmd','$ cmd'扩展得很好,并运行命令。 – Daenyth 2012-03-29 15:49:30

相关问题