I am trying to create a shell script with a simple functionality, but it seems I can not wrap my head about how to handle backslashes correctly. One of my functions look like this:
#!/bin/sh
func() {
cmd="$*"
printf "%s\n" "$cmd"
echo -e $cmd
}
func '%{NAME}\\n'
This is the correct output, as I need it:
%{NAME}\\n
%{NAME}\n
Now the problem is, I can not use "echo -e", as this script needs to be run on *nix system, where the echo command does not have the "-e" flag (HPUX for instance), that also why I have to use sh and not bash. As I want to make this script as portable as possible, I'd stay clear of using tr/sed or (even worse) script languages.
The format of the input string can be chosen arbitrarily. I was using %{NAME} of a reason, because if it was only regular chars, something like this would work:
#!/bin/sh
func() {
cmd="$*"
printf "%s\n" "$cmd"
printf $cmd
echo
}
func 'NAME\\n'
Unfortunately this breaks with characters such as "%":
%{NAME}\\n
func.sh: line 6: printf: `{': invalid format character
How can I get the desired result, (hopefully) only by using printf, which in my understanding is the most portable function to use?
You can use
%b
inprintf
:Then call it as:
This will print: