【发布时间】: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/bashshebang,它将由cron运行默认情况下在 posix 兼容模式下(使用sh解释器而不是bash),并且您的许多脚本无法按预期工作,这可以解释不同的输出