Creating an output file with multi line script using echo / linux
You need to escape the backticks (`):
#!/bin/bashecho "yellow=\`tput setaf 3\`bel=\`tput bel\`red=\`tput setaf 1\`green=\`tput setaf 2\`reset=\`tput sgr0\`" >> output.txt
As a bonus:
I prefer using this method for multiline:
#!/bin/bashcat << 'EOF' >> output.txtyellow=$(tput setaf 3)bel=$(tput bel)red=$(tput setaf 1)green=$(tput setaf 2)reset=$(tput sgr0)EOF
Use single quote to prevent expansions:
echo 'yellow=`tput setaf 3`bel=`tput bel`red=`tput setaf 1`green=`tput setaf 2`reset=`tput sgr0`' >> output.txt
For more details see Difference between double and single quote.
If your text includes single quote then the above may not work. In that case using a here doc would be safer. For example, the above will break if you insert a line: var='something'
.
Using a here doc it will be like this:
cat >> output.txt <<'EOF'yellow=`tput setaf 3`bel=`tput bel`red=`tput setaf 1`green=`tput setaf 2`reset=`tput sgr0`var='something'EOF
Just a late addition:
The echo 'string' >> output
command is simple and great. But it may will give you the '...: Permission denied' error combined with sudo
.
I recently had a lil issue with sudo echo 'string \n other string \n' > /path/to/file
What worked for me the best:printf "Line1\nLine2\nLine3" | sudo tee --append /path/to/file
It's an extra that you actually have the string printed to the stdout too, so you will see what was written to the file.