【问题标题】:How to write a bc calculated variable to file using CRON jobs (linux, bash, script, cron)如何使用 CRON 作业(linux、bash、脚本、cron)将 bc 计算变量写入文件
【发布时间】:2021-05-08 21:13:02
【问题描述】:

我对这种行为感到很困惑。
每次我从终端运行此脚本时,它都可以正常工作,但一旦从 crontab 执行它就会失败。
在脚本中,您可以找到每个步骤的说明。
目标是使用 peso 变量将日期和时间打印到文件中。
我已经无数次改变了第16行。第 4 行也是如此。

为清楚起见进行编辑:这只是整个脚本的一小部分。
它每分钟都运行良好。除了 peso 问题之外,它什么都做。

请帮忙!!!

1 # Here I compute one decimal value (like z=0.123) with two integers (sd and mean)
2 peso=$( echo "scale=4; ${z}*${sd}/100 + ${mean}/100" | bc -l) 
3 echo "peso_mtrx="$peso       # This is for checking: shows 40.123 (example), so it is OK
4 peso+=";"                    # Add a semicolon to check its behaviour
5 echo "peso= "$peso           # show it: OK
6 peso1=$(date "+%D %T")       # Now I capture date and time
7 echo "fecha= "$peso1         # shows it, so it is OK
8 peso1+=";"                   # add a semicolon to date
9 peso1+=$peso                 # concatenate the peso variable
10 echo $(printf '%s' "$peso1") # shows it, so it is ok up to here

11 echo $(printf '%s' "$peso1") >> ~/projects/Files/normal.csv           # WRITE TO FILE

12 # whenever I run this script from terminal, all variables showed right and even print all data into file.
13 # File stores a new line like:  02/03/21 08:24:40;40.1709; 

14 # BUT... when it is executed from a CRON job... everything except peso are stored.
15 # File stores a line like:  02/03/21 08:24:40;; peso variable just vanishes.

16 # is it something related to subshells? how to solve this rigmarole?

【问题讨论】:

  • 尝试将输出重定向到文件以查看使用 cron 执行时发生了什么
  • 如果你想让 bash 运行它,第一行应该是#!/bin/bash
  • 拉曼,感谢您的关注。第 12 行到第 15 行写的内容显示了我写入文件时发生的情况。这是在第 11 行完成的。从终端运行的文件中的实际输出:02/04/21 08:44:20;40.1370;并从 CRON 运行:02/04/21 08:45:02;;
  • 嗨 Roadwol... 这只是整个脚本的一部分。除了比索变量之外,它实际上运行良好。
  • Roadowl 提到的内容是相关的,您的代码是否是更大脚本的一部分并不意味着它无关紧要:如果您的脚本没有#!/bin/bash shebang,它将由cron 运行默认情况下在 posix 兼容模式下(使用 sh 解释器而不是 bash),并且您的许多脚本无法按预期工作,这可以解释不同的输出

标签: linux bash shell cron


【解决方案1】:

正如我所怀疑的那样,整个事情都与 subshel​​l 问题有关。
我刚刚在 crontab 中做了一些事情。
一旦我执行crontab -e,我最初有类似的东西:

*/1 * * * * /absolute/path/to/project.sh

所以做了一些阅读我最终这样做了:

SHELL=/bin/bash
*/1 * * * * exec bash -l /absolute/path/to/project.sh

我恳请专家就此解决方案向我们提供指导。据我了解,它与使用存储在.bash_profile 中的信息在 cron 中创建登录 shell 有关。
它确实使环境变量可以访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2012-08-14
    相关资源
    最近更新 更多