bash脚本中的sed输出在CLI中工作,cron中的输出不同



在我的Webinoly Ubuntu 18服务器上列出站点的简单脚本在CLI中工作,但在cron中失败。Webinoly是一个站点管理脚本,它有一个列出其管理的站点的命令:

site -list

CLI中此命令的输出如下所示:

- catalyst.dk39ecbk3.com
- siteexample3.com
- webinoly.dk39ecbk3.com

我遇到问题的脚本(下面(应该使用sed删除控制字符、每行开头的"-"和空行:

#!/bin/bash
# create array of sites using webinoly 'site' command
# webinoly site -list command returns lines that start with hyphens and spaces, along with control chars, which need to be removed
# SED s/[x01-x1Fx7F]//g removes control characters
# SED s/.{7}// removes first seven chars and s/.{5}$// removes last 5 chars
# SED /^s*$/d removes blank lines
# removing characters http://www.theunixschool.com/2014/08/sed-examples-remove-delete-chars-from-line-file.html
# removing empty lines https://stackoverflow.com/questions/16414410/delete-empty-lines-using-sed
SITELIST=($(/usr/bin/site -list | sed -r "s/[x01-x1Fx7F]//g;s/.{7}//;s/.{5}$//;/^s*$/d"))
#print site list
for SITE in ${SITELIST[@]}; do
echo "$SITE"
done

以下是我在CLI中看到的所需输出:

root@server1 ~/scripts # ./gdrive-backup-test.sh
catalyst.dk39ecbk3.com
siteexample3.com
webinoly.dk39ecbk3.com

当脚本在cron中运行时,就会出现问题。这是cron文件:

root@server1 ~/scripts # crontab -l
SHELL=/bin/bash
MAILTO=myemail@gmail.com
15 3 * * 7 certbot renew --post-hook "service nginx restart"
47 01 * * * /root/scripts/gdrive-backup-test.sh > /root/scripts/output-gdrive-backup.txt

这是cron命令生成的output-gdrive-backup.txt文件:

root@server1 ~/scripts # cat output-gdrive-backup.txt
lyst.dk39ecbk3
example3
noly.dk39ecbk3

每行的前三个字符缺失,最后四个字符(The.com(也缺失

我已经研究并确保在cron文件中以及在脚本的开头强制使用bash。

使用以下输入:

$ cat site 
- catalyst.dk39ecbk3.com
- siteexample3.com
- webinoly.dk39ecbk3.com
- webinoly.dk39ecbk3.com

您可以使用以下sed命令到达您的输出:

$ cat site | sed -e "s/^s*-s*//g;/^s*$/d"
catalyst.dk39ecbk3.com
siteexample3.com
webinoly.dk39ecbk3.com
webinoly.dk39ecbk3.com

用要从中筛选输出的命令替换cat site

答案是未能在cron文件中指定TERM。这解决了我的主要问题。这是一个奇怪的问题——很难研究和弄清楚。

还有其他一些——其中之一是其中一个命令的路径不是cron使用的路径的一部分,而是包含在CLI的用户根目录中。有关TERM问题的更多信息,请参阅";tput:没有$TERM的值并且没有指定-T";CRON进程记录的错误。

最新更新