从 Shell 脚本创建、写入和保存文件

nta*_*ris 12 scripts nano files

我不想手动编写文件,所以我做了一个shell脚本。有没有办法在不让用户按键的情况下自动写入和保存文件?

sudo nano blah
#write stuff to file
#save file
#continue
Run Code Online (Sandbox Code Playgroud)

^ 这将在 *.sh 文件中

还是有另一种方法可以在脚本中创建一个简单的文本文件?

ste*_*ver 16

对于更复杂的命令序列,您应该考虑使用cat带有here 文档的命令。基本格式是

command > file << END_TEXT
some text here
more text here
END_TEXT
Run Code Online (Sandbox Code Playgroud)

根据 END_TEXT 标签是带引号的还是不带引号的,有两种微妙的不同行为:

  1. 不带引号的标签:内容是在通常的 shell 扩展之后写入的

  2. 引用标签:here 文档的内容按字面处理,没有通常的 shell 扩展

例如考虑以下脚本

#!/bin/bash

var1="VALUE 1"
var2="VALUE 2"

cat > file1 << EOF1
do some commands on "$var1" 
and/or "$var2"
EOF1

cat > file2 << "EOF2"
do some commands on "$var1" 
and/or "$var2"
EOF2
Run Code Online (Sandbox Code Playgroud)

结果是

$ cat file1
do some commands on "VALUE 1" 
and/or "VALUE 2"
Run Code Online (Sandbox Code Playgroud)

$ cat file2
do some commands on "$var1" 
and/or "$var2"
Run Code Online (Sandbox Code Playgroud)

如果您从脚本中输出 shell 命令,您可能需要带引号的形式。


War*_*ill 9

没有必要用编辑器来做这件事。

您可以使用简单的 echo 命令将某些内容附加到文件中。例如

echo "Hello World" >> txt
Run Code Online (Sandbox Code Playgroud)

将“Hello world”附加到文件中txt。如果文件不存在,它将被创建。

或者如果文件可能已经存在并且您想覆盖它

echo "Hello World" > txt
Run Code Online (Sandbox Code Playgroud)

对于第一行:和

echo "I'm feeling good" >> txt
echo "how are you" >> txt 
Run Code Online (Sandbox Code Playgroud)

对于后续线路。

在最简单的情况下,.sh脚本可以只包含一组 echo 命令。