Bash script regex



我是bash的新手,我有一个关于解析命令输出的问题。我有3个进程具有相同的名称"进程",该进程有一些参数,例如:

 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`

这给了我正在运行的进程,我必须查看哪个进程没有运行,并在"a"参数的帮助下重新启动它。

我怎样才能做到这一点?

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 %sn' "$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

您可以编写一个包装器脚本来启动流程并对其进行监控

一般流程为.

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

watcher.sh:

#!/bin/bash
pid=$(pgrep -f 'process $1 $2')
[[ -z $pid ]] || wait $pid
echo "process $@: restarted"
process $@
exec $0 $@

并为每个进程启动自己的观察程序:

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 ... &

相关内容

  • 没有找到相关文章