Use environment variables in crontab (you can manually execute shell scripts, but not in scheduled tasks)

Source: Internet
Author: User

How to reference defined environment variables in crontab
A shell script/root/test/Shell/test_crontab_env.sh uses an environment variable test_crontab_env = test_crontab_env.
Test_crontab_env exists in/etc/profile.
For example:
#! /Bin/bash
Echo "'date + % Y-% m-% d" "% H: % m: % s' $ test_crontab_env">/tmp/test_crontab_env.file
Run the command manually. The running result is as follows:
2010-09-04 11:23:38 test_crontab_env
Add to crontab as follows
*/1 *****/root/test/Shell/test_crontab_env.sh
Result:
$> CAT/tmp/test_crontab_env.file
2010-09-04 11:25:01
2010-09-04 11:26:01
...
The environment variable referenced here is invalid.

How to Make environment variables take effect in crontab:
1. Method of passing Parameters
Crontab
*/1 *****/root/test/Shell/test_crontab_env.sh "test_crontab_env"
Test_crontab_env.sh
#! /Bin/bash
Echo "'date + % Y-% m-% d" "% H: % m: % s' $1">/tmp/test_crontab_env.file
2. Define environment variables in the shell script
Test_crontab_env.sh
#! /Bin/bash
Test_crontab_env = test_crontab_env
Echo "'date + % Y-% m-% d" "% H: % m: % s' $ test_crontab_env">/tmp/test_crontab_env.file
3. Load the environment variable file in the shell script
#! /Bin/bash
Source/etc/profile
Echo "'date + % Y-% m-% d" "% H: % m: % s' $ test_crontab_env">/tmp/test_crontab_env.file

I personally think the third method is the most practical.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.