将shell参数存储在文件中,同时保留引用

时间:2011-05-20 12:10:27

标签: bash shell awk sh

如何将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)引用和/或任何类型的(重要)空格,因此问题变得复杂,因此无条件地在每个参数周围放置单引号或双引号或者每行存储一个参数将不起作用。

2 个答案:

答案 0 :(得分:5)

为什么举重?

storeargs() {
     while [ $# -gt 0 ]
     do 
         printf "%q " "$1"
         shift
     done   
}

你现在可以

storeargs "some" "weird $1 \`bunch\` of" params >  myparams.txt
storeargs "some" 'weird $1 \`bunch\` of' params >> myparams.txt
cat myparams.txt

输出

some weird\ \ \`bunch\`\ of params
some weird\ \$1\ \\\`bunch\\\`\ of params

答案 1 :(得分:1)

此版本每行存储一个参数,因此在存储方面可能有点难看。我怀疑它是完全健壮的,但它满足你的例子(对于useargs(){for i in“$ @”; do echo $ i; done;}):

storeargs() { printf "%q\n" "$@"; } > store

if test -n "$1"; then
  useargs "$@"
  storeargs "$@"
else
  eval useargs $args
fi

- EDIT-- 在printf中使用%q来引用字符串(从sehe的答案中无耻地复制)。请注意,%q在bash内置printf中可用,但在标准printf中不可用。

相关问题