Bash 中的 Cat EOF
Fumbani Banda
2023年1月30日
Bash
Bash Cat
Bash EOF

本教程解釋了 cat EOF 是什麼以及它在 bash 中的用法。
Bash 中的 Cat EOF
cat
是一個 bash 命令,用於讀取、顯示或連線檔案的內容,而 EOF
代表 End Of File
。EOF
向 shell 表明正在讀取的檔案已經結束。cat << eof
使用 here-document
。重定向運算子 <<
和 <<-
都允許將 shell 讀取的後續行重定向到命令的輸入。重定向的行稱為 here-document
。
here-document
使用以下格式。
[n] << word
here-document
delimeter
here-document
被視為在下一個換行符之後開始的單個單詞。它一直持續到有一行只包含分隔符或一個新行,中間沒有空白字元。
將多行字串放入 Bash 中的檔案
cat
、<<
、EOF
和 >
提供了一種將多行字串輸入到檔案中的互動方式。EOF
被稱為 Here Tag
。Here Tag
告訴 shell 你將輸入一個多行字串直到 Here Tag
。<<
用於設定 Here Tag
。>
用於將輸入內容重定向到指定的檔案,在我們的例子中是 multiline.txt
。
cat << EOF > multiline.txt
> This is the first line
> This is the second line
> This is the third line
> EOF
我們還可以使用 cat
、<<
、EOF
和 >
以互動方式編寫如下所示的 bash 指令碼。
cat << EOF > script.sh
#!/bin/bash
printf "Hello\n"
printf "Wordl!\n"
EOF
在 Bash 中將多行字串傳遞給管道
下面的程式碼使用 cat
、eof
和管道將多行輸入字串內容重定向到指定的管道和命令。輸入通過管道傳輸到 grep 命令,grep 字串 A
,匹配的輸入通過管道傳輸到 tee
命令。tee
命令將輸入複製到 fruits.txt
檔案。
cat <<EOF | grep 'A' | tee fruits.txt
> Apple
> Orange
> Apricot
> Banana
> EOF
讓我們用 cat
檢查 fruits.txt
檔案的內容。
cat fruits.txt
輸出:
Apple
Apricot
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Fumbani Banda