简体   繁体   中英

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

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

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.

Thanks to chepner

Best solution I 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 text goes to output file without modifications and color definitions are working without modifications too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM