如何使用echo命令编写和追加到文件

use*_*742 16 shell scripting

我正在尝试编写一个脚本,它将使用echo和write/append到文件.但我已经在字符串中使用了""..说..

echo "I am "Finding" difficult to write this to file" > file.txt
echo "I can "write" without double quotes" >> file.txt
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助理解这一点,真的很感激.

BR,SM

Dev*_*lus 22

如果要使用引号,则必须使用反斜杠字符对它们进行转义.

echo "I am \"Finding\" difficult to write this to file" > file.txt echo
echo "I can \"write\" without double quotes" >> file.txt
Run Code Online (Sandbox Code Playgroud)

如果你也想写\自己也是如此,因为它可能会导致副作用.所以你必须使用\\

另一个选择是使用'''而不是引号.

echo 'I am "Finding" difficult to write this to file' > file.txt echo
echo 'I can "write" without double quotes' >> file.txt
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下,变量替换不起作用,因此如果要使用变量,则必须将它们放在外面.

echo "This is a test to write $PATH in my file" >> file.txt
echo 'This is a test to write '"$PATH"' in my file' >> file.txt
Run Code Online (Sandbox Code Playgroud)


Joe*_*nux 16

如果您有特殊字符,您可以使用反斜杠将它们转义以根据需要使用它们:

echo "I am \"Finding\" difficult to write this to file" > file.txt
echo "I can \"write\" without double quotes" >> file.txt
Run Code Online (Sandbox Code Playgroud)

但是,您也可以在tee命令中使用 shell 的“EOF”功能,这对于编写各种内容非常有用:

tee -a file.txt <<EOF

I am "Finding" difficult to write this to file
I can "write" without double quotes
EOF
Run Code Online (Sandbox Code Playgroud)

这将几乎将您想要的任何内容直接写入该文件,并转义任何特殊字符,直到您到达EOF.

*编辑添加附加开关,以防止覆盖文件:
-a

  • 好的。但区分 `&gt; file.txt` 和 `&gt;&gt; file.txt` 会很有用:`&gt; file.txt`:用新文本 `&gt;&gt; file.txt` 覆盖文件的上下文:将新文本推送到现有上下文 (2认同)