首页 > 解决方案 > 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

标签: bashcronexplodeifs

解决方案


我的脚本是 UTF-8 格式的,因此它们对于配置为使用 ASCII 的 cron 并不真正有效。在我的 bash 脚本中添加以下内容可以解决问题,而无需对 cron 配置进行任何更改。

LC_ALL_SAVED="$LC_ALL"
export LC_ALL=de_DE.UTF-8

现在从 CLI 和 cron 一切都运行良好。谢谢您的帮助。


推荐阅读