【问题标题】:Running a shell script for a certain duration运行 shell 脚本一段时间
【发布时间】:2016-01-04 23:49:33
【问题描述】:

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

#!/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 found。也许我在这里错过了一些重要的东西。

【问题讨论】:

  • 应该是while (( ... )); do 而不是while $(( ... )); do。该行末尾的冒号应该是;(或者可以像所有分号一样删除)。
  • 这个web page 给出了一些例子
  • @Benjamin W. 我编辑了 sn-p 以反映您的建议,但未发现行为差异。
  • @vmachan,您分享的链接似乎已损坏。
  • 嗯,主要的建议是删除while $(( ... )) 行中的外部$ 并删除该行末尾的冒号。

标签: linux bash shell time


【解决方案1】:

几个问题:

  • 条件构造是while (( ... )); do 而不是while $(( ... )); do
  • 行尾的冒号

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-18
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多