Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ...

like image 423
Zaza Avatar asked Nov 12 '16 11:11

Zaza


People also ask

How do I echo multiple lines to a file?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

How do you create a multi line command in Linux?

Using a Backslash. The backslash (\) is an escape character that instructs the shell not to interpret the next character. If the next character is a newline, the shell will read the statement as not having reached its end. This allows a statement to span multiple lines.

How do I add lines to a file in Linux?

There are two standard ways of appending lines to the end of a file: the “>>” redirection operator and the tee command. Both are used interchangeably, but tee's syntax is more verbose and allows for extended operations.


1 Answers

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
like image 70
Nick Avatar answered Oct 22 '22 16:10

Nick