bash 脚本执行日期/时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2073153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:33:18  来源:igfitidea点击:

bash script execution date/time

linuxbashdate

提问by Daniil

I'm trying to figure this out on and off for some time now. I have a bash script in Linux environment that, for safety reasons, I want to prevent from being executed say between 9am and 5pm unless a flag is given. So if I do ./script.sh between 9am and 5pm it would say "NO GO", but if I do ./script.sh -force it would bypass the check. Basically making sure the person doesn't do something by accident. I've tried some date commands, but can't wrap that thing around my mind. Could anyone help out?

我现在正试图断断续续地弄清楚这一点。我在 Linux 环境中有一个 bash 脚本,出于安全原因,我想防止在上午 9 点到下午 5 点之间执行,除非给出标志。因此,如果我在上午 9 点到下午 5 点之间执行 ./script.sh,它会说“NO GO”,但如果我执行 ./script.sh -force 它将绕过检查。基本上确保这个人不会意外地做某事。我已经尝试了一些日期命令,但无法将那件事环绕在我的脑海中。有人可以帮忙吗?

采纳答案by Ignacio Vazquez-Abrams

Write a function. Use date +"%k"to get the current hour, and (( ))to compare it.

写一个函数。使用date +"%k"得到当前小时,(( ))以进行比较。

回答by Jonathan Leffler

Basic answer:

基本答案:

case "" in
(-force)
    : OK;;
(*)
    case $(date +'%H') in
    (09|1[0-6]) 
        echo "Cannot run between 09:00 and 17:00" 1>&2
        exit 1;;
    esac;;
esac

Note that I tested this (a script called 'so.sh') by running:

请注意,我通过运行测试了这个(一个名为“so.sh”的脚本):

TZ=US/Pacific sh so.sh
TZ=US/Central sh so.sh

It worked in Pacific time (08:50) and not in Central time (10:50). The point about this is emphasizing that your controls are only as good as your environment variables. And users can futz with environment variables.

它适用于太平洋时间 (08:50) 而不是中部时间 (10:50)。关于这一点的重点是强调您的控件仅与您的环境变量一样好。用户可以使用环境变量进行测试。

回答by Keith Reynolds

This works

这有效

#!/bin/bash

# Ensure environmental variable runprogram=yes isn't set before 
unset runprogram 

# logic works out to don't run if between 9 and 5pm as you requested
[ $(date "+%k")  -le 9 -a  $(date +"%k")  -ge 17 ] && runprogram=yes  

# Adding - avoids the need to test if the length of  is zero
[ "${}-" = "-forced-" ] && runprogram=yes 

if [ "${runprogram}-" = "yes-" ]; then 
    run_program 
else 
    echo "No Go" 1>&2 #redirects message to standard error
fi

回答by Eduardo

Test script:

测试脚本:

#!/bin/bash

HOUR=$(date +%k)
echo "Now hour is $HOUR"

if [[ $HOUR -gt 9 ]] ; then
  echo 'after 9'
fi


if [[ $HOUR -lt 23 ]]; then
  echo 'before 11 pm'
fi