POSIX Shell backslash confusion

随声附和 提交于 2019-12-13 15:13:42

问题


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:


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}



来源:https://stackoverflow.com/questions/30818982/posix-shell-backslash-confusion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!