I have a very simple .sh script to kill a process. The processes saves its PID to pid2.txt.

pkill -e -P $(cat pid2.txt)

When I run this as sudo ./myscript.sh from the command line it works fine.

When run by cron as */2 * * * * /etc/mylocation/myscript.sh it throws an error:

cat: pid2.txt: No such file or directory pkill: option requires an argument -- 'P'

What am I doing wrong?

  • 3
    Add the full path of pid2.txt in your script, it will then work – Arushix Jun 21 '18 at 5:32
  • Great, I will add it as the answer – Arushix Jun 21 '18 at 5:42
  • I'm unfamiliar with the -e flag for pkill. What does it do on your system, and what Unix are you using? – Kusalananda Jun 21 '18 at 6:02
  • Ubuntu 16.04. -e echoes which PID was killed. – sjaak Jun 21 '18 at 7:02

The cron job is not necessarily running with the same working directory that you happen to have in the interactive session. This means that the file pid2.txt might not be available where you think it is. Change the script so that it uses an absolute path to the pid2.txt file.

You may also remove exit from the end of the script. It serves no purpose.


Add the full path of pid2.txt in your script, it will then work

Explanation: cron jobs run in a very minimal environment, and since they're executed directly by crond without a shell (unless you force one to be created), the regular shell setup never happens. Hence you need to explicitly specify path of all files, scripts being called by cron

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.