bash - 逐字捕获命令行(包括引号!)以调用内部脚本

标签 bash shell

我正在尝试编写一个“phone home”脚本,它将准确的命令行(包括使用的任何单引号或双引号)记录到 MySQL 数据库中。作为后端,我有一个包装数据库的 cgi 脚本。脚本本身在 cgi 脚本上调用 curl 并包含各种参数作为参数,包括逐字命令行。

很明显,我有很多引文要转义到这里,但我已经停留在 bash 阶段了。目前,我什至无法让 bash 逐字打印所提供的参数:

期望的输出:

$ ./caller.sh -f -hello -q "blah"
-f hello -q "blah"

使用 echo :

调用者.sh:

echo "$@"

给出:

$ ./caller.sh -f -hello -q "blah"
-f hello -q blah

(我也试过 echo $@echo $*)

使用 printf %q:

调用者.sh:

printf %q $@
printf "\n"

给出:

$ ./caller.sh -f hello -q "blah"
-fhello-qblah

(我也试过 print %q "$@")

我不仅欢迎帮助解决我的 bash 问题,而且欢迎任何关于以更整洁的方式实现此“电话之家”的更一般性建议!

最佳答案

您无法通过编写 caller.sh 来区分在 shell 上调用的这两个命令:

./caller.sh -f -hello -q "blah"
./caller.sh -f -hello -q blah

完全等价。

如果要确保命令接收特殊字符,请用单引号将参数括起来:

./caller.sh -f -hello -q '"blah"'

或者,如果您只想将一个参数传递给 caller.sh:

./caller.sh '-f -hello -q "blah"'

关于bash - 逐字捕获命令行(包括引号!)以调用内部脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23893692/

相关文章:

linux - Bash 脚本 FS 使用

python - cp: cannot stat ‘/mnt/ask78b30/TEST_FILE’ : 远程 I/O 错误

perl - grep 变量并给出信息输出

bash - 如何检查while循环是否被执行?

linux - 如何安装或切换到旧版本的 GNU Parallel?

bash - 在 bash 中并行运行多个命令

c - 如何将 'ls' 命令转换为 'cat' 命令?

python - 在 python shell 中, "b"字母不起作用,什么?

c++ - 帮助编辑代码以修复 "Argument list too long"错误

bash - 如何修复错误 agrep : pattern too long (has > 32 chars) it doesn't show error if there is no full stop in the string?