相关疑难解决方法(0)

POSIX sh相当于Bash的printf%q

假设我有一个#!/bin/sh可以采用各种位置参数的脚本,其中一些可能包含空格,两种引号或两种引号等.我想迭代"$@"并为每个参数立即以某种方式处理它,或者保存以供以后使用.在脚本结束时,我想启动(可能exec)另一个进程,传递一些这些参数,所有特殊字符都保持不变.

如果我没有对参数进行处理,othercmd "$@"那么工作正常,但我需要提取一些参数并稍微处理它们.

如果我可以假设Bash,那么我可以printf %q用来计算我eval以后可以引用的args的引用版本,但这不适用于例如Ubuntu的Dash(/bin/sh).

是否printf %q可以使用内置函数和POSIX定义的实用程序在简单的Bourne shell脚本中编写任何等效文件,比如说我可以复制到脚本中的函数?

例如,脚本以ls相反的顺序尝试其参数:

#!/bin/sh
args=
for arg in "$@"
do
    args="'$arg' $args"
done
eval "ls $args"
Run Code Online (Sandbox Code Playgroud)

适用于许多情况:

$ ./handle goodbye "cruel world"
ls: cannot access cruel world: No such file or directory
ls: cannot access goodbye: No such file or directory
Run Code Online (Sandbox Code Playgroud)

但不是在'使用时:

$ ./handle goodbye "cruel'st world"
./handle: 1: eval: Syntax error: Unterminated quoted …
Run Code Online (Sandbox Code Playgroud)

bash quotes printf posix sh

18
推荐指数
2
解决办法
3094
查看次数

在Perl正则表达式替换命令行中使用bash变量名作为匹配替换

我正在尝试用shell中与之匹配的bash变量的值替换由字符串中的字符分隔的子字符串。

到目前为止,我已经尝试过了,但没有成功:

varone="noob"
vartwo="trivial"
echo "my {varone} and {vartwo} question" | perl -pe 's|(.*){(\w+)}(.*)|${1}'$(echo "${'${2}'}")'${3}|g'
Run Code Online (Sandbox Code Playgroud)

但是我得到:

bash: ${'${2}'}: bad substitution
Run Code Online (Sandbox Code Playgroud)

关于如何执行此操作的任何想法?提前致谢!

regex bash shell perl command-line

3
推荐指数
2
解决办法
75
查看次数

标签 统计

bash ×2

command-line ×1

perl ×1

posix ×1

printf ×1

quotes ×1

regex ×1

sh ×1

shell ×1