天天看點

shell腳本之重定向、标準輸入、輸出、錯誤輸出的使用

linux    shell腳本

大量重複執行的工作 

shell (Linux殼), 一類程式的名稱

文本檔案-------> shell指令, /bin/bash提供邏輯控制語句, 

重定向符号的使用 

/dev/stdin 标準輸入裝置(鍵盤) 0

/dev/stdout 标準輸出裝置(顯示器) 1

/dev/stderr 标準錯誤輸出裝置(顯示器)  2

輸出重定向符号

>  >> 用于重定向标準輸出

[root@shell ~]# ls -ldh /etc/ > /tmp/1.txt

[root@shell ~]# ls -ldh /tmp/ >> /tmp/1.txt 

2>  2>> 用于重定向标準錯誤輸出 

[root@shell ~]# ls -ldh /asjdfklasjdlfasd 2> /tmp/1.txt 

&> 同時重定向标準輸出及标準錯誤輸出 

特殊裝置檔案: /dev/null 

[root@shell ~]# ls -ldh /etc/ &> /dev/null 

輸入重定向符号

[root@shell ~]# tr 'a-z' 'A-Z' < /tmp/1.txt 

ABCDEF

[root@shell ~]# 

[root@localhost ~]# mail -s "test fstab" root@localhost < /etc/fstab 

輸出資訊:

1 echo 

[root@shell ~]# echo "請輸入你的選擇:" 預設會列印換行符

請輸入你的選擇:

[root@shell ~]# echo -n "請輸入你的選擇:"

請輸入你的選擇:[root@shell ~]# 

[root@shell ~]# echo -e "a\nbb\nccc" \n:回車   或者\r

a

bb

ccc

[root@shell ~]# echo -e "a\tbb\tccc" \t tab鍵

a bb ccc

[root@shell ~]# 

2 printf

[root@shell ~]# printf "hello world"

hello world[root@shell ~]# 

3 HERE DOCUMENT -----> 輸出多行内容 

[root@shell ~]# cat << eof

> 1. 安裝KVM

> 2. 重置所有虛拟機

> eof

1. 安裝KVM

2. 重置所有虛拟機

[root@shell ~]# 

雙引号和單引号的差別:

單引号: 所有字元會失雲原有的含義 

雙引号: 特殊字元會被轉義

如何處理互動式指令:

[root@shell ~]# echo "redhat" | passwd --stdin tom &> /dev/null 

[root@shell ~]# echo -e "n\np\n1\n\n+500M\nw\n" | fdisk /dev/vdb &> /dev/null 

本文轉自 北冥有大魚  51CTO部落格,原文連結:http://blog.51cto.com/lyw168/1957399,如需轉載請自行聯系原作者

繼續閱讀