There are multiple ways to do it, let's run this script called exercise.sh
#!/usr/bin/env bash
> file1.txt cat <<< "This is a here-string with random value $RANDOM"
# Or if you prefer to see what is happening and write to file as well
tee file2.txt <<< "Here is another here-string I can see and write to file"
# if you want to work multiline easily
cat <<EOF > file3.txt
You don't need to escape any quotes here, $ marks start of variables, unless escaped.
This is random value from variable $RANDOM
This is literal \$RANDOM
EOF
# Let's say you have a variable with multiline text and you want to manipulate it
a="
1
2
3
33
"
# Assume I want to have lines containing "3". Instead of grep it can even be another script
a=$(echo "$a" | grep 3)
# Then you want to write this to a file, although here-string is fine,
# if you don't need single-liner command, prefer heredoc
# Herestring. (If it's single liner, variable needs to be quoted to preserve newlines)
> file4.txt cat <<< "$a"
# Heredoc
cat <<EOF > file5.txt
$a
EOF
This is the output you should see:
$ bash exercise.sh
Here is another here-string I can see and write to file
And files should contain these:
$ ls
exercise.sh file1.txt file2.txt file3.txt file4.txt file5.txt
$ cat file1.txt
This is a here-string with random value 20914
$ cat file2.txt
Here is another here-string I can see and write to file
$ cat file3.txt
You don't need to escape any quotes here, $ marks start of variables, unless escaped.
This is random value from variable 15899
This is literal $RANDOM
$ cat file4.txt
3
33
$ cat file5.txt
3
33