I'm executing a shell script and one of the commands is creating a file with text via echo.
However, if the text within echo has "\t" or similar, it automatically translates it into a TAB character, same goes for other special characters.
I know that if I put another "\" before it would ignore it and proceed as desired.
echo 'This is a test and want \t to be just a text' > newfile
ex:
\t => TAB (notok)
\\t => \t (ok)
But I don't intend to search for possible scenarios every time I run the script and was looking to create the file using print or similar (hoping that there is another way to remove this automatic translation of special chars. ) but I'm not so familiar with this function yet.
echo will give undetermined results across shells and/or platforms when using special characters. The best way to get predictable behavior is to use printf with a format specifier.
printf '%s\n' 'This is a test and want \t to be just a text'
should reliably and constantly produce the output you require in any Posix or Bourne type shell across platforms.....
---
To get consistent echo behavior, you could add a simple function at the start of the script, that overrides the echo builtin and emulates the desired echo behavior (without the -n option)
echo ()
{
printf "%s\n" "$*"
}
This should work, provided IFS is set to the standard $' \t\n' (space-tab-newline).
--
But to create a text file I would use a here document instead of printf commands..
For example
cat <<EOF >file
text
text\text2
text\text2\ntext3
text\text2\ntext3 text4
EOF
Note that the second EOF has to be at the start of the line
Your suggestion using a here document worked best for all purposes. I don't even have to worry about quotes and double quotes using this solution. The script is much more improved now.
Thank you very much.
EDITED: With this option, I just realized that I'm not able to input dollar sign as text, it will remove the entire variable. Do you have a workaround for this too without having to put \ before the $ sign?