【问题标题】:Why date is not updated in Linux Shell Script?为什么 Linux Shell 脚本中的日期没有更新?
【发布时间】:2021-05-06 01:33:46
【问题描述】:

我创建了一个 shell 脚本来创建 cron 以每 5 分钟清理一次内存缓存,并在 cron 工作时将其记录到日志文件 cron_test 中。我的脚本如下。但是,当我第一次运行这个脚本时,日期戳仍然存在,它没有更新!例如,如果我在 2021 年 2 月 1 日星期一晚上 11:47:55 的时间运行下面的脚本,那么它会在每一行连续写下“clean_ram 工作 @ 2021 年 2 月 1 日星期一晚上 11:47:55 EST”!如何将日期更新为 cron 成功工作的时间?

    #!/bin/sh
    
    cat  <<EOF1 > /home/clean_ram.sh
    #!/bin/sh
    exec sudo -s <<'EOF'
    sync; echo 1>/proc/sys/vm/drop_caches # clean ram cache
    echo "clean_ram worked @ `date`" >> /home/cron_test
    EOF1

    echo "EOF" >> /home/knoppix/clean_ram.sh # add EOF to the end of clean_ram.sh file manually

    # make it exevutable 
    chmod a+x /home/knoppix/clean_ram.sh

    echo "[IS4] creat cron list in crontab"
    (crontab -l; echo "*/5 * * * * /home/clean_ram.sh"| crontab -

【问题讨论】:

  • 您是否考虑过在文本编辑器中打开 /home/clean_ram.sh 并查看它的行为方式?
  • 使用cat &lt;&lt; 'EOF1' &gt; /home/clean_ram.sh,即使用非插值的heredoc
  • 实际上是的。我已经打开了它,我看到的是我写的,包括 EOF 行。这是EOF的问题吗?你指出来了吗?

标签: linux shell date cron


【解决方案1】:

您使用的是插值 heredoc,所以

`date`

在heredoc 扩展时被插值。只需引用分隔符即可防止这种情况发生。另外,不是 1992 年。请使用 $()

cat  << 'EOF1' > /home/clean_ram.sh
#!/bin/sh
exec sudo -s <<'EOF'
sync; echo 1>/proc/sys/vm/drop_caches # clean ram cache
echo "clean_ram worked @ $(date)" >> /home/cron_test
EOF1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2015-04-14
    • 2012-10-27
    • 2013-08-25
    相关资源
    最近更新 更多