【问题标题】:Unable to access value from for loop in shell script when run from cron从 cron 运行时,无法从 shell 脚本中的 for 循环访问值
【发布时间】:2011-10-28 18:36:42
【问题描述】:

这是我第一次涉足 shell 脚本,所以如果我要问一个非常基本的问题,请对我温柔一点!

我有一个 shell 脚本,它通过 FTP 下载文件,使用 split 将文件分成单独的小文件。然后我使用 for 循环调用一个 PHP 文件,该文件对文件进行一些处理,这个 PHP 进程在后台运行以完成。

这 2 个脚本组合在 sudo 下从命令行运行时运行良好,但是从 cron 运行时,我似乎无法将文件名值传递给 PHP。

我的2个测试脚本如下

shell-test.sh

#!/bin/bash

cd /path/to/directory/containing/split/files/

#Split the file into seperate 80k line files
split -l 80000 /path/to/file/needing/to/be/split/

#Get the current epoch time as all scripts will need to use the same update time
epochtime=$(date +"%s")

echo $epochtime

#Output a list of the files in the directory
ls


#For loop to run through each file in the working directory
#For each file we run the php script with safe mode off (to enable access to includes)
#We pass in the name of the file and epochtime
#The ampersand at the end of the string runs the file in the background in parallel so     that all scripts execute concurrently

for file in *
do
php -d safe_mode=Off /path/to/php/script/shell-test.php -f $file -t $epochtime &
done

#Wait for all scripts to finish
wait

shell-test.php

<?php

$scriptOptions = getopt("f:t:");

print_r($scriptOptions);

?>

当从命令行运行时,输出以下是我需要的 - 文件值被传递给 PHP 脚本。

1319824758
xaa  xab  xac  xad
Array
(
[f] => xaa
[t] => 1319824758
)
Array
(
[f] => xac
[t] => 1319824758
)
Array
(
[f] => xad
[t] => 1319824758
)
Array
(
[f] => xab
[t] => 1319824758
)

但是,当通过 cron 运行时,会输出以下内容

1319825522
xaa
xab
xac
xad
Array
(
[f] => *
[t] => 1319825522
)

所以我需要知道的是如何将 * 的值作为文件名而不是实际的字符串 * (以及为什么会发生这种情况也很有用!)。

【问题讨论】:

    标签: shell parameters cron


    【解决方案1】:

    我的随机猜测是,为了安全起见,cron 正在运行带有 -f 选项的 shell。尝试添加

    set +f
    

    到你的脚本。或者找到其他枚举文件的方法。

    【讨论】:

    • 很好用——非常感谢!必须阅读更改此选项后运行 cron 的影响。有人可以为这个特定主题的相对菜鸟推荐一个体面的资源吗?
    猜你喜欢
    • 2011-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2016-05-27
    • 2018-08-28
    相关资源
    最近更新 更多