在命令运行时执行bash循环 [英] executing bash loop while command is running

查看:84
本文介绍了在命令运行时执行bash循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个执行命令并同时执行其他任务的bash脚本,如果脚本被杀死,则有可能杀死该命令.说,执行一个大文件的cp,同时打印自复制开始以来经过的时间,但是如果脚本被杀死,它也会杀死副本. 我不想要使用rsync,原因有两个:1)运行缓慢,2)我想学习如何做,这可能会很有用. 我试过了:

I want to build a bash script that executes a command and in the meanwhile performs other stuff, with the possibility of killing the command if the script is killed. Say, executes a cp of a large file and in the meanwhile prints the elapsed time since copy started, but if the script is killed it kills also the copy. I don't want to use rsync, for 2 reasons: 1) is slow and 2) I want to learn how to do it, it could be useful. I tried this:

until cp SOURCE DEST
do
#evaluates time, stuff, commands, file dimensions, not important now
#and echoes something
done

,但它不执行do - done块,因为它正在等待副本结束.你能建议点什么吗?

but it doesn't execute the do - done block, as it is waiting that the copy ends. Could you please suggest something?

推荐答案

untilwhile相反.这与运行另一个命令时的工作无关.为此,您需要使用&在后台运行任务.

until is the opposite of while. It's nothing to do with doing stuff while another command runs. For that you need to run your task in the background with &.

cp SOURCE DEST &
pid=$!

# If this script is killed, kill the `cp'.
trap "kill $pid 2> /dev/null" EXIT

# While copy is running...
while kill -0 $pid 2> /dev/null; do
    # Do stuff
    ...
    sleep 1
done

# Disable the trap on a normal exit.
trap - EXIT

kill -0检查进程是否正在运行.注意,顾名思义,它实际上并没有发出信号并杀死它.至少没有信号0.

kill -0 checks if a process is running. Note that it doesn't actually signal the process and kill it, as the name might suggest. Not with signal 0, at least.

这篇关于在命令运行时执行bash循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆