2012-07-10 109 views
0

我是bash的新手,我有一個關於解析命令輸出的問題。我有3個過程具有相同名稱爲「處理」,並且處理有一定的參數,例如:Bash腳本正則表達式

process -a 10 -b 20 -c 30 ... 
process -a 15 -b 30 -c 40 ... 
process -a 30 -b 40 -c 50 ... 

我要處理的「a」參數,並將它們分配給數組是否存在的過程。如果它們不存在,我必須重新啓動這個過程。我在處理過程中有:

`$PS -ef|$GREP -v grep|$GREP process` 

這給了我正在運行的進程,我要看看哪個進程不運行,並與'參數的幫助下重新啓動它。

我該如何做到這一點?

+0

現在我們知道你想做的事,哪來的你的問題? – bos 2012-07-10 08:28:21

+0

@bos。我的問題是我怎麼能做到這一點? – barp 2012-07-10 08:29:36

+0

您可以使用'ps -C process -o cmd ='來獲得更好的命令及其參數列表。 – Sorpigal 2012-07-10 10:33:38

回答

0

你可以寫一個包裝腳本來啓動這個過程並監視它。

通用流量將會是。

var pid_of_bg_process 

func start_process 
process -a 10 -b 20 -c 30 ... & 
pid_of_bg_process=$! 

start_process  
while true 
sleep 1min 
if file not exists /proc/$pid_of_bg_process 
    alert_process_being_restarted 
    start_process 
else 
    continue 
0
in_array() { for v in "${@:2}"; do [[ "$v" = "$1" ]] && return 0; done; return 1; } 

relaunch() { 
    echo "Do whatever you need to do in order to run again with $1" 
} 

watch=(10 15 30) 
running=() 
while read -r proc a av b bv c cv ; do 
    printf 'a was %s, b was %s, c was %s\n' "$av" "$bv" "$cv" # can be omitted 
    running=("${running[@]}" "$av") 
done < <(ps -C process -o cmd=) 

for item in "${watch[@]}" ; do 
    in_array "$item" "${running[@]}" || relaunch "$item" 
done 
0

watcher.sh:

#!/bin/bash 

pid=$(pgrep -f 'process $1 $2') 
[[ -z $pid ]] || wait $pid 

echo "process [email protected]: restarted" 
process [email protected] 
exec $0 [email protected] 

,並開始爲每個進程自己的守望者:

nohup ./watcher.sh -a 10 -b 20 -c 30 ... & 
nohup ./watcher.sh -a 15 -b 30 -c 40 ... & 
nohup ./watcher.sh -a 30 -b 40 -c 50 ... &