重定向
重定向
几乎所有命令都会将输出产生到屏幕上或从键盘上获取输入,但是在
在
Standard File | File Descriptor Number | Meaning | Example (type at shell prompt) |
---|---|---|---|
stdin | 0 | Read input from a file (the default is keyboard) | cat < filename |
stdout | 1 | Send data to a file (the default is screen). | date > output.txtcat output.txt |
stderr | 2 | Send all error messages to a file (the default is screen). | rm /tmp/4815162342.txt 2>error.txtcat error.txt |
标准输入
标准输入是默认输入法,所有命令都使用它来读取其输入。用零数字(0)表示。也称为
$ command < filename
$ cat < /etc/passwd

标准输出
命令使用标准输出来写入(显示)其输出。默认为屏幕,用一个数字(1)表示。也称为标准输出。默认的标准输出是屏幕。
$ command > output.file.name
$ ls > /tmp/output.txt

要简单地重定向输出,请使用以下语法:
command > /path/to/file
/path/to/script.sh > output.txt
例如,将
date > now.txt
You can also use the > operator to print file, enter:
cat file.txt > /dev/lp0
OR
sudo bash -c "cat file.txt > /dev/lp0"
To make a usage listing of the directories in the /home partition, enter:
sudo bash -c "cd /home ; du -s *│ sort -rn >/tmp/usage"
You can also use the following syntax:
echo "Today is $(date)" 1>/tmp/now.txt
You can append the output to the same file using » operator, enter:
date >> now.txt
cat now.txt
You can also use the following syntax:
echo "Today is $(date)" 1>>/tmp/now.txt
标准异常
标准错误是默认错误输出设备,用于写入所有系统错误消息。用两个数字(2)表示,也称为
$ command 2> errors.txt
例如,将查找命令错误发送到名为
find / -iname "*.conf" 2>fileerrors.txt
cat fileerrors.txt

要将标准错误重定向到名为
command-name 2>error.log
在
find /home -name .profile 2>/tmp/error
样本输出:
/home/t2/.profile
/home/vivek/ttt/skel/.profile
要查看错误,请输入:
more /tmp/error
样本输出:
find: `/home/vivek/.cpan/build/Acme-POE-Tree-1.01-qqmq77': Permission denied
find: `/home/vivek/.cpan/build/Lchown-1.00-uOM4tb': Permission denied
find: `/home/vivek/.cpan/build/IO-Tty-1.07-F9rDy3': Permission denied
find: `/home/vivek/.cpan/build/POE-Test-Loops-1.002-9AjIro': Permission denied
find: `/home/vivek/.cpan/build/POE-1.003-KwXVB1': Permission denied
find: `/home/vivek/.cpan/build/Curses-1.27-ZLo169': Permission denied
您可以将脚本错误重定向到名为
./script.sh 2>scripts.err
/path/to/example.pl 2>scripts.err
您可以使用
command-name 2>>error.log
./script.sh 2>>error.log
/path/to/example.pl 2>>error.log
您可以使用以下语法将
command-name &>filename
command-name >cmd.log 2>&1
command-name >/dev/null 2>&1
此语法通常用于
@hourly /scripts/backup/nas.backup >/dev/null 2>&1
@hourly /scripts/backup/nas.backup &>/dev/null