1

I wrote a simple shell script in centOS and executing this from a cron job. My script looks like below:

#!/bin/bash

export PATH=$PATH:$(pwd) 
echo $PATH
echo $PATH| mail -s "PATH" me@gmail.com

And if I execute this script directly from terminal, it outputs below:

/sbin:/bin:/usr/sbin:/usr/bin:/vagrant

where /vagrant is the one I expected.

But if this is executed from cron job, it outputs (in my mail) like:

/usr/bin:/bin:/root

How I can set /vagrant properly when executed from a cron job?

UPDATE: I can set the /vagrant as PATH but it will work for me only. If I deploy my script to some other user, they have to make this directory. So I want to make the script like it will export the location from where it is running.

In my case , my script is running from /vagrant but the current directory is being exported as /root. This is the problem.

UPDATE: Sadly speaking, path was exported correctly but files from the /vagrant directory was reported to be not found.

Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44
  • Well, by specifying `/vagrant`. `$(pwd)` resolves the the current working directory, which depends on the situation. – arkascha May 24 '16 at 09:29
  • `cron` runs in a different environment, so you cannot assume the same values as when you run with your user. If you want to add `/vagrant`, just hardcode it. If you want to use variables, check [Where can I set environment variables that crontab will use?](http://stackoverflow.com/a/37183809/1983854) – fedorqui May 24 '16 at 09:29
  • Also, what do yo want to use: the current working directory (pwd) or the directory where the script is? – fedorqui May 24 '16 at 09:31
  • The directory where the script is. – Mahbub Rahman May 24 '16 at 09:32
  • For this part you may want to check [Can a Bash script tell what directory it's stored in?](http://stackoverflow.com/q/59895/1983854). – fedorqui May 24 '16 at 09:52

1 Answers1

1

A cron job runs in the owner's home directory, so that's what pwd results in when it runs. Just put the directory you want instead.

PATH=$PATH:/vagrant

Incidentally, you can't (reliably) use the Bash syntax export variable=value because Cron runs plain sh. Anyway, there should be no need to export the PATH variable, because it is already exported, inherently (it couldn't work if it wasn't).

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • cron can run whatever you ask it to, doesn't it? You can say `* * * * * /bin/bash /home/me/script.sh`. – fedorqui May 24 '16 at 09:46
  • 1
    @fedorqui You are correct of course; though one possible error is if the OP isn't running the script through the shebang, or is specifying `sh` explicitly in spite of the shebang. Anyway, I guess this is moot now. – tripleee May 24 '16 at 10:44