POSIX Shell backslash confusion

250 views Asked by At

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?

1

There are 1 answers

1
anubhava On BEST ANSWER

You can use %b in printf:

func() { cmd="$@"; printf "%s\n%b" "$cmd" "$cmd"; }

Then call it as:

func '%{NAME}\n\n'

This will print:

%{NAME}\n\n
%{NAME}