Friday, May 3, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  19] [ 0]  / answers: 1 / hits: 144522  / 1 Year ago, mon, november 21, 2022, 6:42:46

I don't want to write the file manually, so I made a shell-script.
Is there a way to write & save the file automatically without getting the user to press keys?



sudo nano blah
#write stuff to file
#save file
#continue


^ This will be inside a *.sh file



Or is there another way to create a simple text file in a script?


More From » files

 Answers
7

For more complex sequences of commands you should consider using the cat command with a here document. The basic format is



command > file << END_TEXT
some text here
more text here
END_TEXT


There are two subtly different behaviors depending whether the END_TEXT label is quoted or unquoted:




  1. unquoted label: the contents are written after the usual shell expansions


  2. quoted label: the contents of the here document are treated literally, without the usual shell expansions




For example consider the following script



#!/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


The results are



$ cat file1
do some commands on "VALUE 1"
and/or "VALUE 2"


and



$ cat file2
do some commands on "$var1"
and/or "$var2"


If you are outputting shell commands from your script, you probably want the quoted form.


[#26051] Monday, November 21, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
measord

Total Points: 259
Total Questions: 131
Total Answers: 106

Location: Venezuela
Member since Sun, Oct 2, 2022
2 Years ago
;