linux 输入/输出重定向,linux重定向


文件描述符(fd)是与某个打开的文件或数据流相关联的整数。文件描述符0,1,2是系统预留的。

0 ---- stdin(标准输入)
1 ---- stdout(标准输出)
2 ---- stderr(标准错误)   

输入重定向的命令 < ,输出重定向的命令 > ;
错误重定向的命令 2>,追加重定向的命令 >> ;

重定向到文件

mkdir /tmp/10
cd /tmp/10
echo "123" > 1.txt
echo "456" >> 1.txt
cat 1.txt
#123
#456

ls + #错误重定向
#ls: cannot access +: NO such file or directory
ls + 2> 1.txt
cat 1.txt
#ls: cannot access +: NO such file or directory

#还可以将stderr转换成stdout,使得stderr和stdout都被重定向到同一文件
#cmd > output.txt 2>&1   或者 cmd &> output.txt
ls + > output.txt 2>&1   #ls + &> output.txt
cat output.txt
#ls: cannot access +: NO such file or directory

#重定向到空设备
#/dev/null是一个空设备,向它写入的数组都会丢弃,但返回状态是成功的
ls + > /dev/null 2>&1
echo $?
#2 表示上条命令没有执行成功
#利用它的返回状态常用if判断中,如:
#检查多个主机是否存活 
for ip in 192.168.217.{1..3};do
        if ping -c 1 $ip >/dev/null;then
        #ping不通则为false
                echo "$ip ok"
        else
                echo "$ip no!"
        fi
done

redirect.sh

#!/bin/bash
cat << EOF >log.txt
Log file head
this is a test log file
function :system statistics
EOF

在cat << EOF >log.txt与下一个EOF之间的所有文本都会被当做stdin数据。log.txt的内容如下:

sh redirect.sh
cat log.txt
#Log file head
#this is a test log file
#function :system statistics

read命令
read命令从标准输入中读取,并把读取的内容复制给变量。

#-p prompt  提示信息
read -p "please input your name:" name
#please input your name:James
echo $name
#James

#-a array   保存为数组,元素以空格分隔
read -p "please input your hobby:" -a arr
#please input your hobby:basketball pingpang running
echo ${arr[*]}
#basketball pingpang running

#read -d delimiter 持续读取直到遇到delimiter第一个字符退出
read -p "please input number of not 5:" -d 5
#please input number of not 5:4
#6
#5  遇到5返回

#-s 隐藏输入
#-t timeout 等待超时时间,秒


cat a.txt
#a b c
#1 2 3
#x y z
#while循环按行读取文件
cat a.txt |
while read line;do
echo $line
sleep 1
done

#重定向读取
while read line;do
echo $line
sleep 1
done < a.txt

#for循环读取
old_IFS=$IFS
IFS="\n"
for i in `cat a.txt`;do
echo $i
sleep 1
done
IFS=$old_IFS


#分别变量赋值
read a b c
#1 2 3
echo $a $b $c
#1 2 3
版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/cxs123678/article/details/79359841

相关内容

    暂无相关文章