bash - bash IFS 因终端和 cron 执行而异
问题描述
我有一个文件 sortedurls.txt,它是逐行抓取域到 URL 的结果。sortedurls.txt 看起来像这样
https://example.com/page1.php
https://example.com/page2.php
https://example.com/page-more.php
逐行循环sortedurls.txt(逐个url)并使用wget和hxselect从页面中收集img标签。仅用于验证保存到文件 testtagstring.txt。这看起来像这样
<img alt="…" src="/assets/…/image1.jpg">§<img alt="…" src="/assets/…/image11.jpg">
<img alt="…" src="/assets/…/image2.jpg">§
等等
将分隔符 § 处的每一行拆分为数组“标签”。计算数组元素并将结果附加到文件以进行验证。
问题:在终端中执行正常,输出显示正确数量的条目(6、1、1、9 ...)。从 cronjob 执行,IFS 将数量翻倍,达到 12、2、2、18 ...。
知道为什么这只是通过使用通过 cron 来改变它的行为吗?
#!/bin/bash
# Set this script dir path
scriptdirpath=/usr/local/www/apache24/data/mydomain.com/testdir
# Some config variables
useragent=googlebot
searchtag=img
delimiter=§
# Change to pwd
cd $scriptdirpath
# Make files
echo > testtagstring.txt
echo > testimages.txt
# Loop through the sortedurls.txt
while read p; do
tagString=$(wget -qO - --user-agent="$useragent" $p | hxnormalize -x | hxselect -s "$delimiter" $searchtag )
echo $tagString >> testtagstring.txt
IFS="$delimiter" read -r -a tags <<<"$tagString"
echo "Amount of img tags: ${#tags[@]}" >> $scriptdirpath/testimages.txt
done < $scriptdirpath/sortedurls.txt
解决方案
我的脚本是 UTF-8 格式的,因此它们对于配置为使用 ASCII 的 cron 并不真正有效。在我的 bash 脚本中添加以下内容可以解决问题,而无需对 cron 配置进行任何更改。
LC_ALL_SAVED="$LC_ALL"
export LC_ALL=de_DE.UTF-8
现在从 CLI 和 cron 一切都运行良好。谢谢您的帮助。
推荐阅读
- php - “必需”属性在 PHP HTML 中不起作用
- javascript - 在 node.js 中将 .voc 音频转换为 wav
- php - 致命错误:在 null 上调用成员函数 query() - 仅在本地服务器上的 Web 服务器上没有问题
- enums - 为什么字符串不是 Elixir 中的枚举?
- javascript - 扩展运算符 ES5 等效
- elasticsearch - 如何将特定格式的文档导入 Elasticsearch?
- c++ - 类初始化器列表不适用于复制构造函数
- omnet++ - Veins_Inet 示例:omnet ++
- r - R,dplyr包,获取每天的收盘价
- reactjs - 在 docker nginx 中未定义 React 环境变量