Shell

如何將多行附加到文件

  • February 24, 2022

我正在編寫一個 bash 腳本來查找文件,如果它不存在然後創建它並將其附加到它:

Host localhost
   ForwardAgent yes

所以"line then new line 'tab' then text"我認為它是一種敏感的格式。我知道你可以這樣做:

cat temp.txt >> data.txt

但它似乎很奇怪,因為它有兩條線。有沒有辦法以這種格式附加它:

echo "hello" >> greetings.txt
# possibility 1:
echo "line 1" >> greetings.txt
echo "line 2" >> greetings.txt

# possibility 2:
echo "line 1
line 2" >> greetings.txt

# possibility 3:
cat <<EOT >> greetings.txt
line 1
line 2
EOT

如果需要 sudo(其他使用者權限)來寫入文件,請使用:

# possibility 1:
echo "line 1" | sudo tee -a greetings.txt > /dev/null

# possibility 3:
sudo tee -a greetings.txt > /dev/null <<EOT
line 1
line 2
EOT
echo -e "Hello \nWorld \n" >> greetings.txt

引用自:https://unix.stackexchange.com/questions/77277