linux 輸入 輸出重定向

2021-08-15 18:19:29 字數 2776 閱讀 4401

檔案描述符(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.;do

if ping -c 1

$ip >/dev/null;then

#ping不通則為false

echo

"$ip ok"

else

echo

"$ip no!"

fidone

redirect.sh

#!/bin/bash

cat << eof >log.txt

log file head

this

is a test log file

function

:system

statistics

eof

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

$#basketball pingpang running

#read -d delimiter 持續讀取直到遇到delimiter第乙個字元退出

read -p "please input number of not 5:"-d5

#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

$isleep 1

done

ifs=$old_ifs

#分別變數賦值

read a b c

#1 2 3

echo

$a$b

$c#1 2 3

Linux重定向(輸入輸出重定向)

我們知道,linux 中標準的輸入裝置預設指的是鍵盤,標準的輸出裝置預設指的是顯示器。而本節所要介紹的輸入 輸出重定向,完全可以從字面意思去理解,也就是 通常是用檔案或命令的執行結果來代替鍵盤作為新的輸入裝置,而新的輸出裝置通常指的就是檔案。對於輸入重定向來說,其需要用到的符號以及作用如表 1 所示...

linux輸入輸出重定向

基本概念 這是理解後面的知識的前提,請務必理解 a i o重定向通常與 fd有關,shell的fd通常為10個,即 0 9 b 常用fd有3個,為0 stdin,標準輸入 1 stdout,標準輸出 2 stderr,標準錯誤輸出 預設與keyboard monitor有關 c 用 來改變讀進的資料...

Linux輸入輸出重定向

標準輸入輸出 裝置 裝置檔名 檔案描述符 型別鍵盤 dev stdin 0標準輸入 顯示器 dev stdout 1標準輸出 顯示器 dev stderr 2標準錯誤輸出 輸出重定向 輸出重定向符號 1 標準輸出重定向 命令 檔案 以覆蓋方式把命令的正確輸出重定向到檔案或裝置 命令 檔案 以追加的方...