@JaySon
2017-04-16T15:27:34.000000Z
字数 1317
阅读 3619
Blog
Linux
写程序的时候, 一般都会遇到 stdin, stdout, stderr 三个默认文件描述符(file descriptor).
名称 | 类型 | 文件描述符 | 操作 |
---|---|---|---|
stdin 标准输入 | standard input | 0 | < ,<< |
stdout 标准输出 | standard output | 1 | > ,>> |
stderr 标准错误输出 | standard error output | 2 | 2> ,2>> |
平时运行小型的程序, 都通过直接打印到屏幕上看输出就好, 但是在下面两种状况, 通常都会需要用到输出重定向
* 输出很多的时候, 特别是在debug的时候, 通过重定向到文件, 然后对log进行搜索
* 配置好定时任务运行, 当想查看定时任务的运行日志的时候, 查看脚本的运行状况
下面是一段用于测试的Python程序
➜ ~ > cat test.py
#!/usr/bin/env python
#encoding=utf-8
from __future__ import print_function
import sys
if __name__ == '__main__':
print("Output to stdout")
print("Output to stderr", file=sys.stderr)
# 把stdout重定向
python test.py > test.log
# 把stderr绑定到stdout中
python test.py > test.log 2>&1
# 与上一个命令同样效果
python test.py &> test.log
# stdout重定向到 /dev/null (Linux下特殊的"黑洞"设备描述符, 相当于抛弃所有stdout输出)
python test.py > /dev/null
crontab文件每一行的格式:M H D m d cmd
M: 分钟(0-59)。
H:小时(0-23)。
D:天(1-31)。
m: 月(1-12)。
d: 一星期内的天(0~6,0为星期天)。
cmd要运行的程序,程序被送入sh执行,这个shell只有USER,HOME,SHELL这三个环境变量
crontab -e
: 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数
来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
crontab -r
: 删除目前的crontab !!!慎用!!!
crontab -l
: 列出目前的crontab内容
注: crontab -r
这一命令比较坑爹, r在e旁边, 一个不小心可能会按错吧crontab清空, (曾经不小心按错导致清空了服务器上的crontab, 一个晚上都在找crontab的备份来进行还原)在编辑crontab时谨慎一些.
目前我编辑crontabb之前, 都先使用crontab -l
先把当前的crontab打印到标准输出, 然后再编辑, 这样即使编辑错了, 还能根据打印到屏幕的内容来进行恢复
一般运行定时任务, 还会把脚本的log记录下来, 后面好回溯定时任务执行得是否正确, 一般写成下面的形式
0 1 * * * /path/to/script &> /path/to/script/log &