gpt4 book ai didi

linux - 运行 shell 脚本一段时间

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:42 25 4
gpt4 key购买 nike

我希望能够在 Linux shell (bash) 上运行脚本一段时间并休眠不同的时间。我写了类似以下代码片段的内容。但是,我只看到 sleep 正确发生,但执行在第一次执行后停止。

#!/bin/bash
some_work(){
echo "Working for $1 minutes"
if [ $1 -gt 0 ]
then
echo "Setting timer for $1 minutes"
run_end_time=$(($1 * 60))
start_time=SECONDS
curr_time=SECONDS
while $((curr_time < $((start_time + run_end_time)) )) :
do
#Do some work here
curr_time=SECONDS
done
fi
}

sleep_time(){
echo "Sleeping for $1 minutes"
sleep $(($1 * 60))
}

if [ $# -gt 1 ]
then
echo "Starting Steeplechase run for $1/$2"
while :
do
some_work $1
sleep_time $2
done
fi

我得到的响应是 ./script.sh: line 30: 1: not find。也许我在这里错过了一些重要的事情。

最佳答案

几个问题:

  • 条件结构是 while (( ... ));执行 而不是while $(( ... ));做
  • 行尾的冒号

    while $((curr_time < $((start_time + run_end_time)) )) :

    一定不在那里。

  • 当您需要变量的值时,您可以分配字符串SECONDS;分配应类似于 var=$SECONDS 而不是 var=SECONDS

完整的脚本,包含一些建议和我的缩进想法:

#!/bin/bash

some_work () {
echo "Working for $1 minutes"
if (( $1 > 0 )); then
echo "Setting timer for $1 minutes"
run_end_time=$(($1 * 60))
start_time=$SECONDS
curr_time=$start_time # Want this to be the same value
while ((curr_time < $((start_time + run_end_time)) )); do
#Do some work here
curr_time=$SECONDS
done
fi
}

sleep_time () {
echo "Sleeping for $1 minutes"
sleep $(($1 * 60))
}

if (( $# > 1 )); then
echo "Starting Steeplechase run for $1/$2"
while true; do
some_work $1
sleep_time $2
done
fi

关于linux - 运行 shell 脚本一段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com