3

I need to send a personal env variable $FTP111_PASSWD defined at my personal .bashrc to crontab execution. How to set an environment variable on crontab?

My original shell script, named cron4_etc.sh, created for crontab execution was:

#!/bin/bash cd /myFolder/ ftp -n -i <<EOF open 101.111.111.111 user myUser "$FTP111_PASSWD" mget check_*.log bye EOF 

If I execute the script via terminal ./cron4_etc.sh it is executing fine, but if I have start it using the following crontab line

 */20 * * * * /home/myUser/cron4_etc.sh > /tmp/cron4.log 2>&1 

crontab says

Password: Login incorrect.\nLogin failed.

I tried to improve my script using this suggestion, but the error persists:

#!/usr/bin/env bash # set environment source /home/myUser/.bashrc cd /tmp/pg_io/PGW ftp -n -i <<EOF open 101.111.111.111 user myUser "$FTP111_PASSWD" mget check_*.log bye EOF 

PS: I am using Ubuntu 18 LTS, but the question is for generic crontab.

2
  • Did you check out the answers to this post and especially this one, which explains the pitfalls of using Ubuntu’s default .bashrc in non-interactive shells? Commented May 7, 2020 at 1:30
  • Thanks @amain, make sense. The correct question seems this two steps: 1. Where the best place to my $FTP_etc_PASSWD variables, .bash_profile? 2. how to "run this place" at my Crontab script? ... Or the best is put in /etc/environment ? Commented May 7, 2020 at 4:05

1 Answer 1

9
+50

My favorite solution comes from Augusto Destrero, who provided the following answer to a very similar question:

Setting vars in /etc/environment also worked for me in Ubuntu. As of 12.04, variables in /etc/environment are loaded for cron.

Some people suggest to do a simple env >> /etc/environment to append all your environment variables, but I would be careful with that and rather review /etc/environment manually.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi B--rian, thanks, good clues and explanations! Can you show a script? (I will copy/paste and test it, I need a full "recipe for dummies").. Need to start with #!/bin/bash or other magic that you must explain.
.... Seem that it is not the best answer at cited answer page, the best is the simplest and runs with UBUNTU 20 LTS also, is a simple "add -l option", see here.
Well, my solution does not really require a script, and I just said that it is my preferred solution for Ubuntu since it bundles all environment variables on a single location. bash -lworks as well, and so does the accepted answer of the question I quoted.
Oops, @amain remember that is not a good practice to run .bashrc on crontab... So, your answer shows the best choice and a good practice. I tested and crontab is running /etc/environment!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.