標准IO(Standard Input/Output)
可用於做輸入的設備:
鍵盤設備、文件系統上的常規文件、網卡等。
可用於做輸出的設備:
顯示器、文件系統上的常規文件、網卡等。
程序的數據流有三種:
- 輸入的數據流:<– 標准輸入(
stdin
(standard input)),默認接受來自鍵盤的輸入。 - 輸出的數據流:–> 標准輸出(
stdout
(standard output)),默認輸出到終端窗口。 - 錯誤輸出流:–> 標准錯誤(
stderr
(standard error)),默認輸出到終端窗口。
fd
:file descriptor,文件描述符
標准輸入:0
標准輸出:1
標准錯誤:2
echo $?
(bash腳本編程中,很多判斷基於$?
這個來決定)
IO重定向(Input/Output Redirection)
輸入本來默認是鍵盤,我們改成其他輸入,就是輸入重定向 :例如從文本文件里輸入。
本來輸出的位置是顯示器,我們改成其他輸出,就是輸出重定向:例如輸出到文件。
set -C
:
禁止覆蓋輸出重定向到已存在的文件(在這種模式下,如果你非要覆蓋,可以使用
>|
)
set +C
:
關閉上述特性
/dev/null
特殊設備,空設備,也叫黑洞,數據進去都沒了。
輸出重定向(Output Redirection)的幾種方法
1. 正常輸出重定向:
>
(覆蓋輸出)、>>
(追加輸出)例子:
2. 錯誤輸出重定向:
2>
(覆蓋輸出)、2>>
(追加輸出)
123 ls /etc/issue1111 2>> /tmp/error.outcatt /etc/issue 2>> /dev/null正確和錯誤的都進行輸出重定向:
- 新寫法:
COMMAND &> /path/to/somefile
、COMMAND &>> /path/to/somefile
- 老寫法:
COMMAND > /path/to/somefile 2>&1
、COMMAND >> /path/to/somefile 2>&1
1234 ls /boot /err &> /tmp/all1.log # 新寫法ls /boot /err &>> /tmp/all2.log # 新寫法ls /boot /err > /tmp/all3.log 2>&1 # 老寫法ls /boot /err >> /tmp/all4.log 2>&1 # 老寫法
輸入重定向(Input Redirection)的方法
tr
命令
tr [OPTION]... SET1 [SET2]
把輸入的數據當中的字符,凡是在SET1
定義范圍內出現的,通通對位轉換為SET2
出現的字符
tr SET1 SET2 < /path/from/somefile
對位轉化SET1中的字符為SET2中的字符tr -d SET1 < /path/from/somefile
刪除指定集合里出現的字符tr -s "\n" /path/from/somefile
把指定的連續的字符以一個字符表示,壓縮。tr -c
Complement ,取字符集的補集,通常與其他參數結合使用,例如-dc
123456789101112 [root❄centos7 ~]☭ tr 'a-z' 'A-Z'aabbcc33AABBCC33^C[root❄centos7 ~]☭ tr 'a-z' 'A-Z' </etc/issue\SKERNEL \R ON AN \M[root❄centos7 ~]☭ tr 'a-z' 'A-Z' < /etc/issue > /app/issue2[root❄centos7 ~]☭ cat /app/issue2\SKERNEL \R ON AN \Mtips:如果是輸入后再輸出到同一個文件,就會清空這個文件,所以最好不要這么用,下面是一個錯誤示范:
12345 [root❄centos7 ~]☭ cd /app/[root❄centos7 app]☭ cp issue2 issue3[root❄centos7 app]☭ tr 'a-z' 'A-Z' < issue3 >issue3[root❄centos7 app]☭ cat issue3[root❄centos7 app]☭追加是可以的,在原有文件基礎上再追加一段:
1234567891011 [root❄centos7 app]☭ cat issue2\SKERNEL \R ON AN \M[root❄centos7 app]☭ tr 'A-Z' 'a-z' < issue2 >> issue2[root❄centos7 app]☭ cat issue2\SKERNEL \R ON AN \M\skernel \r on an \mdc結合使用
123456789 [root❄centos7 app]☭ echo {a..z} >f1[root❄centos7 app]☭ cat f1a b c d e f g h i j k l m n o p q r s t u v w x y z[root❄centos7 app]☭ tr -d 'f-n' <f1a b c d e o p q r s t u v w x y z[root❄centos7 app]☭ cat f1a b c d e f g h i j k l m n o p q r s t u v w x y z[root❄centos7 app]☭ tr -dc 'f-n' < f1fghijklmn[root❄centos7 app]☭Here documents
輸出到屏幕,或創建多行文檔):
<<終止詞
例子:
123456789101112131415161718192021 [root❄centos7 app]☭ cat <<EOF> yulongjun> zhaoweiqiang> EOFyulongjunzhaoweiqiang[root❄centos7 app]☭ cat >cat.out <<END> yulongjun> zhaoweiqiang> hanjinze> songda> END[root❄centos7 app]☭ cat /tmp/cat.outyulongjunzhaoweiqianghanjinzesongda
-
代表輸出流搭配
cat
cat -
:如果指定cat的文件為-,表示從標准輸入讀取(和直接使用cat,好像沒什么區別)搭配
|
echo 123 | cat -
:表示把管道符前面的輸出流,在交給cat執行一遍(這就很牛逼了)例子:
如果操作系統沒有scp命令,只有ssh,那么是不是就不能遠程拷貝了(前提:沒有openssh-clients軟件包)
利用
-
,就可以實現:
1 cat jdk.tar.gz | ssh 192.168.56.101 'cat - > /tmp/jdk.tar.gz'
cat jdk.tar.gz
產生輸出流, 在管道后面的-
,則可以接受輸出流,並重定向到/tmp/jdk.tar.gz