Bash script: perform actions based on file contents

谁说胖子不能爱 提交于 2019-12-25 04:39:07

问题


I have a bash script that loops through all folders inside a given path and performs some actions.

I now need this script to find the given path by itself, by monitoring a file that I will update from my server.

So, the script has to:

  1. check if file todo.txt exists
  2. read the first line of the file
  3. perform actions inside the folder defined in that first line
  4. delete todo.txt
  5. append done.txt with the same line it found in todo.txt

For some reason, when I run the script directly, this works perfect

cd /proper/path/to/todo
FILE=todo.txt
if [ -f $FILE ];
then
    FOLDER=$(head -1 $FILE)
    echo "path to process:"$FOLDER
fi;

The output is good, the file is read, the output is "path to process: /correct/path/read/from/file"

However, when I set up a cron job to run this script, the $FOLDER variable is empty so the output is just "path to process:"

* * * * * /bin/sh /www/www.mysite.com/myscript.sh >> /www/www.mysite.com/log.txt

Note that: 1. the script IS ran 2. the if [ -f $FILE ] works, so the file is found

It's just the head command that fails.

Any ideas? thanks!


回答1:


It sounds like /usr/bin is not in cron's PATH. Try this: add this entry into cron

* * * * * env > $HOME/cron.env

Wait a minute and see what that file says.


Don't parse ls -- instead of for i in $(ls) do for file in *. Since for iterates over words, any filename with whitespace will not be handled properly



来源:https://stackoverflow.com/questions/20273733/bash-script-perform-actions-based-on-file-contents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!