Running a simple shell script as a cronjob

后端 未结 5 1746
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 11:57

I have a very simple shell script I need to run as a cronjob but I can\'t get even the test scripts to run. Here\'s and example script:

/home/myUser/scripts/test.sh<

5条回答
  •  天涯浪人
    2020-12-16 12:19

    What directory is file.txt in? cron runs jobs in your home directory, so unless your script cds somewhere else, that's where it's going to look for/create file.txt.

    EDIT: When you refer to a file without specifying its full path (e.g. file.txt, as opposed to the full path /home/myUser/scripts/file.txt) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.

    Thus, if you cd (change working directory) to the directory the script's in and then run it, file.txt will refer to a file in the same directory as the script. But if you don't cd there first, file.txt will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh or /home/myUser/scripts/test.sh; ./test.sh won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).

    When you run a script from cron, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cds somewhere else or specifies an absolute path to the file.

提交回复
热议问题