
问题: 我使用 crontab 做定时任务 。写了一个脚本如下 :
#!/bin/bash cd ~/project/python/spider/spider nohup pipenv run python main.py >> log.txt 2>&1 & 因为环境变量的问题,以上脚本并不能正常执行。 因此我添加了环境变量 :
#!/bin/bash source $HOME/.bash_proifle echo $PATH >> ~/hello.txt cd ~/project/python/spider/spider nohup pipenv run python main.py >> log.txt 2>&1 & 然而我发现使用 source $HOME/.bash_proifle 后,环境变量 $PATH 仍然没有改变。 我必须手动指定 PATH=/home/apple/.local/bin:/home/apple/bin:$PATH crontab 才能正常执行,如下代码 :
#!/bin/bash PATH=/home/apple/.local/bin:/home/apple/bin:$PATH cd ~/project/python/spider/spider nohup pipenv run python main.py >> log.txt 2>&1 & 其中 ~/.bash_profile 内容如下 :
# .bash_profile # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi # User specific environment and startup programs PATH=$PATH:$HOME/.local/bin:$HOME/bin export PATH
1 boris1993 2019 年 3 月 6 日 via Android 直接把 b 变量写在命令前面看看,并且不要涉及$HOME 之类的用户相关的变量 PATH=$PATH:/home/your_name/bin nohup pipenv (略) |
2 xiaket 2019 年 3 月 6 日 你可以做这个实验来看看 cron 是用什么环境变量跑的: ``` * * * * * export > /tmp/cron_env ``` |
3 wlsnx 2019 年 3 月 6 日 你可以看一下.bashrc 或者它 source 的其他文件,看看有没有这种语句 [ -z "$PS1" ] && return |
4 dangyuluo 2019 年 3 月 6 日 看看 stderr of line `source $HOME/.bash_proifle` |
5 shakespaces 2019 年 3 月 6 日 via Android crontab 有时候当前环境搞不清,一般我都直接用绝对路径 |
6 zjlletian 2019 年 3 月 6 日 重启 /usr/sbin/crond |
7 xiaoxinxiaobai 2019 年 3 月 6 日 via Android 你需要知道 crontab 运行一个 task 的时候,$HOME 是啥 |
8 zthxxx 2019 年 3 月 6 日 如果你是在云服务器上, `.bashrc` 文件里通常很可能有 `if [ "$BASH" ]` `if [ -z "$PS1" ] ` stty 之类的语句判断不是 shell 环境就退出; 并且 crontab 是根据 passwd 中启动用户的指向来设置 $HOME 变量的 > Several environment variables are set up automatically by the cron(8) daemon. SHELL is set to /bin/sh, and LOGNAME and HOME are set from the /etc/passwd line of the crontab's owner. https://manpages.debian.org/stretch/cron/crontab.5.en.html |
9 liubin 2019 年 3 月 6 日 用.bashrc 吧,bash_profile 是登录 shell 用的吧。 |
10 Sherlocker 2019 年 3 月 6 日 你可以直接配置 crontab 时直接加上 source ~/.bash_proifle && 执行脚本 ,一点问题都没 |
11 defunct9 2019 年 3 月 6 日 开 ssh,让我上去看看 |
12 rootit 2019 年 3 月 6 日 要用 . source 好像找不到 |
13 alexsunxl 2019 年 3 月 6 日 crontab 尽量用绝对路径, 这个坑踩过几回 |
14 flyingpot 2019 年 3 月 6 日 profile 打错了,是复制的吗 |
15 a15819620038 2019 年 3 月 6 日 via iPhone 全路径 |
16 Beebird 2019 年 3 月 6 日 我倒是觉得先要搞清楚哪处需要 /home/apple/bin 或 home/apple/.local/bin 作为 PATH 的搜索路径。是楼主的 pipenv 和 python ?还是 main.py 里面有例如 subprocess 之类的调用? 找到问题再对症下药。 |
17 sparkssssssss 2019 年 3 月 7 日 via iPhone source /etc/profile |
18 julyclyde 2019 年 3 月 7 日 这种情况,我一般会 strace -f 一下 |