Shell 根据用户输入将文本插入文件最后一行的脚本

Shell script that inserts text to last line of a file based on user input

#!/bin/sh
...
read var
#user enters: it doesn't work
...
echo 'Some text and $var' > myfile.txt

预期输出:

cat myfile.txt
#Some text and it doesn't work

实际输出:

cat myfile.txt
#Some text and $var

那么如何将 $var 变量的值回显到文件中呢?

使用双引号代替单引号使变量替换可用

您也可以删除引号以使其正常工作,但我们不推荐这样做

http://wiki.bash-hackers.org/syntax/quoting

如果你想在最后一行插入$var(=将内容$var附加到文件),请使用>>

应该是:

echo "Some text and $var" >> myfile.txt

> 是覆盖内容,而 >> 是将内容附加到文件