Bash script: perform actions based on file content

2019-09-18 19:40发布

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条回答
Rolldiameter
2楼-- · 2019-09-18 20:17

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

查看更多
登录 后发表回答