Creating an output file with multiple lines of script using echo / linux

Trying to create a small script capable of writing part of a script to an 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 

Required Conclusion:

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

I get:

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

Using CentOS 7 Minimum new installation If you are looking for a solution that will be applied to the full script / text, the line will not change, I think it can be done with sed ...

+5
source share
4 answers

You need to avoid reverse steps ( ` ):

 #!/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 to use this method for multi-line:

 #!/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 
+12
source

Use a single quote to prevent extensions:

 echo ' yellow=`tput setaf 3` bel=`tput bel` red=`tput setaf 1` green=`tput setaf 2` reset=`tput sgr0` ' >> output.txt 

See the difference between a double and a single quote for more details.


If your text contains single quotes, then the above may not work. In this case, using the doc here will be safer. For example, the above will break if you insert the line: var='something' .

Using this document, it will look 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 
+1
source

Thanks chepner

The best solution I have found is:

 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 

With this solution, all the text goes to the output file without changes, and color definitions also work without changes.

0
source

Just the latest addition:

The echo 'string' >> output command is simple and convenient. But this may give you the error "...: Permission denied" in conjunction with sudo .

I recently had a problem with sudo echo 'string \n other string \n' > /path/to/file

What worked best for me:
printf "Line1\nLine2\nLine3" | sudo tee --append /path/to/file

Also, you actually have a line also printed on stdout, so you will see what was written to the file.

0
source

Source: https://habr.com/ru/post/1259627/


All Articles