POSIX Shell 反斜杠混淆 [英] POSIX Shell backslash confusion

查看:52
本文介绍了POSIX Shell 反斜杠混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有简单功能的 shell 脚本,但似乎我无法理解如何正确处理反斜杠.我的功能之一如下所示:

#!/bin/sh功能(){cmd="$*"printf "%s\n" "$cmd"echo -e $cmd}功能'%{NAME}\\n'

这是我需要的正确输出:

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

现在的问题是,我不能使用echo -e",因为这个脚本需要在 *nix 系统上运行,其中 echo 命令没有-e"标志(例如 HPUX),即也是为什么我必须使用 sh 而不是 bash.因为我想让这个脚本尽可能地便携,所以我不会使用 tr/sed 或(甚至更糟的)脚本语言.

输入字符串的格式可以任意选择.我使用 %{NAME} 是有原因的,因为如果它只是普通字符,这样的事情会起作用:

#!/bin/sh功能(){cmd="$*"printf "%s\n" "$cmd"打印 $cmd回声}func 'NAME\\n'

不幸的是,这会被诸如%"之类的字符破坏:

%{NAME}\\nfunc.sh: 第 6 行: printf: `{': 格式字符无效

我怎样才能得到想要的结果,(希望如此)只通过使用 printf,在我的理解中这是最便携的功能?

解决方案

你可以在printf中使用%b:

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

然后将其称为:

func '%{NAME}\n\n'

这将打印:

<前>%{NAME}\n\n%{名称}

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 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}

这篇关于POSIX Shell 反斜杠混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆