Replacing echo with print

Hi everyone,

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.

Do you have any solution for this?

Appreciate the help.

Strange - works fine on Linux under bash.
What's your OS/shell and do you have 'echo' aliased to something else?

Its running with AIX OS.

Shell is currently as #! /usr/bin/ksh

The echo command is just literally as:

echo 'text
text
text
text' > /home/newfile 

Hi,
under bash, you have a set parameter to control these:

$ shopt -s xpg_echo
$ echo 'foo\tbar'
foo	bar
$ shopt -u xpg_echo
$ echo 'foo\tbar'
foo\tbar
$ echo -e 'foo\tbar'
foo	bar

Regards.

1 Like
if [ "$(uname)" == "AIX" ] ; then
  ECHO="print -R"
else
  ECHO="echo"
fi

$ECHO "some text"
1 Like

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

1 Like

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.
:b:
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?

Thanks!

You can make a here-document parse variables literally by beginning it with <<"EOF" instead of <<EOF .

1 Like