Creating an output file with multi line script using echo / linux

29,798

Solution 1

You need to escape the backticks (`):

#!/bin/bash
echo "
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/bash
cat << 'EOF' >> output.txt
yellow=$(tput setaf 3)
bel=$(tput bel)
red=$(tput setaf 1)
green=$(tput setaf 2)
reset=$(tput sgr0)
EOF

Solution 2

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

Solution 3

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.

Share:
29,798
Zaza
Author by

Zaza

Updated on December 29, 2021

Comments

  • Zaza
    Zaza over 2 years

    Trying to create a small script capable to write a part off the script in the output file without any changes, (as is)

    source file text

    echo "
    yellow=`tput setaf 3`
    bel=`tput bel`
    red=`tput setaf 1`
    green=`tput setaf 2`
    reset=`tput sgr0
    echo"#${green}Installing packages${reset}#" &&
    " >> output.txt
    

    Desired output:

    yellow=`tput setaf 3`
    bel=`tput bel`
    red=`tput setaf 1`
    green=`tput setaf 2`
    reset=`tput sgr0
    echo"#${green}Installing packages${reset}#" &&
    

    What I'm getting is:

    yellow=^[[33m
    bel=^G
    red=^[[31m
    green=^[[32m
    reset=^[(B^[[m
    echo"#${green}Installing packages${reset}#" &&
    

    Using CentOS 7 Minimal fresh install Looking for a solution to be applied to the full script/text, no the line per line changes, I suppose may be done using sed too ...