2012-03-29 2 views
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)) 

지금까지뿐만 아니라 동안 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). 그 코드는 무서워! [Code Review] (http://codereview.stackexchange.com/)에 게시하고 싶을 수도 있습니다. – l0b0

답변

0

나는 당신이하는 일에 100 % 명확하지 않다는 것을 인정해야한다. 하지만 난 당신이 변경하려는 생각이에

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

다음 PID 명령 및 msgboxlist라는 배열에 세 개의 새로운 요소로 "OFF"를 추가합니다

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

. 그런 다음 명령에서 "$msgboxlist""${msgboxlist[@]}"으로 변경하여 모든 요소를 ​​명령의 인수로 포함하십시오. 당신은 명령으로 $pid$command을 실행하기 위해 노력하고

1

:

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

좋은 리펙토링. 나는 지금 의도를 실제로 이해할 수 있습니다.awk 'length ($ 0)> l {l = 길이 ($ 0)} END {print l}'' – ghoti

0

변수를 확장하려면 큰 따옴표를 사용하십시오. 변수 확장을 사용하지 않으려면 작은 따옴표를 사용하십시오.

다음은 나중에 실행하기 위해 저장된 명령의 예입니다. 읽기 adressing

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

편집 :

는 일반적으로 전체 라인을 읽고 읽을 사용. 대신에 이것을 고려 (테스트)

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

가 또한 표시 헤더를 건너 '명령을 PS = O를 PID ='의 다른 사용에주의.

+1

'eval $에 대한 필요성이 없기 때문에, cmd','$ cmd'는 잘 확장되어 명령을 실행합니다. – Daenyth

관련 문제