今天在學習部署安裝openstack的時候,看到一個關於cat的奇怪用法,可能是本人的才疏學淺沒見過這種寫法,於是乎查閱資料了一番,並進行了總結,希望也能夠幫助有需要的朋友。
以下是我總結的幾種常用方式:
1. 最普通用法
cat /proc/version
Linux version 2.6.32-5-686 (Debian 2.6.32-38)
等價於:
cat < /proc/version
cat /proc/version -n // 顯示行號
2. 從鍵盤創建一個文件
(1)先看個簡單的:
root@localhost:~# cat // 直接輸入cat命令回車
hello
hello
world
world
ctrl + D // 結束輸入
解釋:cat命令從標准輸入中讀取數據並打印到標准輸出, 因此屏幕上看到的2次信息
(2)再看一個擴展的:
root@localhost:~# cat > file.txt
hello
world
ctrl + D // 相當於EOF的符號
root@localhost:~# cat file.txt // 查看file.txt文件
hello // 將從鍵盤輸入的數據保存在了file.txt中
world
解釋:cat命令從標准輸入讀取數據,並未打印到標准輸出,而是通過>重定向到文件file.txt,達到了從鍵盤創建文件的效果
擴展:>符號會將原來文件覆蓋(如果存在) 如果想要追加鍵盤輸入的內容, 需要將">" -> ">>"即可
3. 合並多個文件內容
root@localhost:~# ls
root@localhost:~# file1.txt file2.txt
root@localhost:~# cat file1.txt
hello
root@localhost:~# cat file2.txt
world
root@localhost:~# cat file1.txt file2.txt > file3.txt // 合並2個文件, 多個文件也是一樣的
root@localhost:~# cat file3.txt
hello
world
注:同理可以合並多個文件
4. Here文檔
(1) 打印到屏幕
root@localhost:~# cat <<EOF
> This is here doc.
> Only used to display.
> The third line.
> EOF
This is here doc.
Only used to display.
The third line.
解釋:這種方式是將EOF標識符中間的內容輸出的標准輸出.
(2) 輸出到文件(>>可以追加)
root@localhost:~# cat <<EOF > output.txt
> This is here doc.
> Only used to display.
> The third line.
> EOF
/* 查看 output.txt 文件 */
root@localhost:~# cat output.txt
This is here doc.
Only used to display.
The third line.
解釋:"EOF"只是個標識符號, 沒有特殊意義, 替換為其它都行.
5. 與管道符"|"符合的結合使用
(1) 先看個示例
root@localhost:~# passwd
Enter new UNIX password: 123456789 // 實際操作中輸入密碼是不顯示的
Retype new UNIX password: 123456789
passwd: password updated successfully
解釋:這里需要分2次輸入要設置的密碼
(2) 使用cat <<EOF可以在方便實現(最重要的是可以在腳本中實現修改密碼)
root@localhost:~# cat <<EOF | passwd
> 123456 // 輸入的第一次密碼
> 123456 // 輸入的第二次密碼
> EOF
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully
解釋:其它需要動態輸入數據的腳本同理可操作.