将 shell 参数存储在文件中,同时保留引用
如何将 shell 参数存储在文件中以供以后使用,同时保留引用?
需要明确的是:我不想传递参数,这可以使用 "$@"
轻松完成。但实际上需要将它们存储在文件中以供以后使用。
#!/bin/sh
storeargs() {
: #-)
}
if "$1"
then
# useargs is actuall 'git filter-branch'
useargs "$@"
storeargs "$@"
else
# without args use those from previous invocation
eval useargs $(cat store)
fi
。
$ foo 'a "b"' "c 'd'" '\'' 'd
e'
$ foo # behave as if called with same arguments again
问题可能归结为如何使用通用工具(awk、perl...)来引用字符串。我更喜欢一个不会使引用的字符串变得不可读的解决方案。 store
的内容应该看起来或多或少类似于我在命令行上指定的内容。
由于要引用的参数/字符串可能已经包含任何类型的有效(shell)引用和/或任何类型的(重要)空格,因此问题变得复杂,因此无条件地在每个参数周围放置单引号或双引号或存储一个每行参数不起作用。
How can shell arguments be stored in a file for later use while preserving quoting?
To be clear: I don't want to pass on the arguments in place, which could be easily done using "$@"
. But actually need to store them in a file for later use.
#!/bin/sh
storeargs() {
: #-)
}
if "$1"
then
# useargs is actuall 'git filter-branch'
useargs "$@"
storeargs "$@"
else
# without args use those from previous invocation
eval useargs $(cat store)
fi
.
$ foo 'a "b"' "c 'd'" '\'' 'd
e'
$ foo # behave as if called with same arguments again
The question likely comes down to how to quote a string using common tools in general (awk, perl, ...). I would prefer a solution that does not make the quoted string unreadable. The content of store
should look more or less like what I would specify on the commandline.
The question is complicated by the fact that the arguments/strings to be quoted might already contain any kind of valid (shell) quoting and/or any kind of (significant) whitespace, so unconditionally putting single or double quotes around every argument or storing one argument per line won't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要举起重物?
您现在可以
输出
Why do the heavy lifting?
You can now
Output
此版本每行存储一个参数,因此在存储方面可能有点难看。我怀疑它是否完全健壮,但它满足您的示例(for useargs() { for i in "$@"; do echo $i; done; } ):
--编辑--
在 printf 中使用 %q 来引用字符串(无耻地从 sehe 的答案中复制)。请注意,%q 在 bash 内置 printf 中可用,但在标准 printf 中不可用。
This version stores the arguments one per line, so may be a bit ugly in terms of storage. I doubt that it is completely robust, but it satisfies your example (for useargs() { for i in "$@"; do echo $i; done; } ):
--EDIT--
Use %q in printf to quote the strings (shamelessly copied from sehe's answer). Note that %q is available in the bash built-in printf, but not in standard printf.