【问题标题】:bash IFS different by terminal and cron executionbash IFS 因终端和 cron 执行而异
【发布时间】:2019-01-30 09:43:42
【问题描述】:

我有一个文件 sortedurls.txt,它是逐行抓取域到 URL 的结果。 sortedurls.txt 看起来像这样

https://example.com/page1.php
https://example.com/page2.php
https://example.com/page-more.php

逐行循环sortedurls.txt(url by 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

【问题讨论】:

  • hxnormalizehxselectcron 的路径上吗?
  • 可能是重点,谢谢。它们在 /usr/local/bin/hx... 但是我怎样才能将这些路径放入 cron 中?
  • 在此脚本中添加新的第二行export PATH=$PATH:/usr/local/bin
  • 在 shebang 之后添加了我的 test.sh 的附加路径。没变。顺便说一句,保存的文件 testtagstring.txt 显示了由我的分隔符 char § 分隔的 img 标签的预期字符串。我很难假设 IFS 是我的问题。

标签: bash cron explode ifs


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多