2012-03-29 198 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

相關問題