linux crontab與環境變數

2021-06-29 12:59:47 字數 1269 閱讀 4241

crontab中使用環境變數的方法

2010-09-04 11:50:29

分類: linux

在crontab中如何引用已定義的環境變數

乙個shell指令碼 /root/test/shell/test_crontab_env.sh,內部使用了乙個環境變數 test_crontab_env=test_crontab_env

且test_crontab_env存在於 /etc/profile 中

如:#!/bin/bash

echo "`date +%y-%m-%d" "%h:%m:%s` $test_crontab_env" >> /tmp/test_crontab_env.file

手動執行, 執行結果:

2010-09-04 11:23:38 test_crontab_env

新增到 crontab 中如下

*/1 * * * * /root/test/shell/test_crontab_env.sh

結果:$> cat /tmp/test_crontab_env.file

2010-09-04 11:25:01

2010-09-04 11:26:01

...這裡引用的環境變數無效了.   

使環境變數在crontab中生效的方法:

1.傳參的方式

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.在該shell指令碼中定義環境變數

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.在該shell指令碼中載入環境變數檔案

#!/bin/bash

source /etc/profile

echo "`date +%y-%m-%d" "%h:%m:%s` $test_crontab_env" >> /tmp/test_crontab_env.file

個人覺得還是第三種方法最實用

Linux crontab 命令格式與詳細例子

基本格式 command 分 時 日 月 周 命令 第1列表示分鐘1 59 每分鐘用 或者 1表示 第2列表示小時1 23 0表示0點 第3列表示日期1 31 第4列表示月份1 12 第5列標識號星期0 6 0表示星期天 第6列要執行的命令 crontab檔案的一些例子 上面的例子表示每晚的21 3...

Linux crontab 命令格式與詳細例子

基本格式 command 分 時 日 月 周 命令 第1列表示分鐘1 59 每分鐘用 或者 1表示 第2列表示小時1 23 0表示0點 第3列表示日期1 31 第4列表示月份1 12 第5列標識號星期0 6 0表示星期天 第6列要執行的命令 crontab檔案的一些例子 上面的例子表示每晚的21 3...

Linux crontab 命令格式與詳細例子

基本格式 command 分 時 日 月 周 命令 第1列表示分鐘1 59 每分鐘用 或者 1表示 第2列表示小時1 23 0表示0點 第3列表示日期1 31 第4列表示月份1 12 第5列標識號星期0 6 0表示星期天 第6列要執行的命令 crontab檔案的一些例子 上面的例子表示每晚的21 3...