Ruslan's excellent answer explains why your command may not be working for you and offers a robust, portable solution.
tl;dr:
- You probably ran your code with
sh
rather than bash
(even though on macOS sh
is Bash in disguise), or you had shell option xpg_echo
explicitly turned on.
- Use
printf
instead of echo
for portability.
In Bash, with the default options and using the echo
builtin, your command should work as-is (except that you should double-quote $old_name
for robustness), because echo
by default does not expand escape sequences such as \t
in its operands.
However, Bash's echo
can be made to expand control-character escape sequences:
- explicitly, by executing
shopt -s xpg_echo
- implicitly, if you run Bash as
sh
or with the --posix
option (which, among other options and behavior changes, activates xpg_echo
)
Thus, your symptom may have been caused by running your code from a script with shebang line #!/bin/sh
, for instance.
However, if you're targeting sh
, i.e., if you're writing a portable script, then echo
should be avoided altogether for the very reason that its behavior differs across shells and platforms - see Ruslan's printf
solution.
As an aside: perhaps a more robust approach to your tr
command is a whitelisting approach: stating only the characters that are explicitly allowed in your result, and excluding other with the -C
option:
old_name='testing\this\folder'
new_name=$(printf '%s' "$old_name" | tr -C '[:alnum:]_-' ' ')
That way, any characters that aren't either letters, numbers, _
, or -
are replaced with a space.
tr -d '[:punct:]'
– Stinky