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

tar*_*ius 3 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
Run Code Online (Sandbox Code Playgroud)

.

$ foo 'a "b"' "c 'd'" '\'' 'd
e'
$ foo # behave as if called with same arguments again
Run Code Online (Sandbox Code Playgroud)

问题可能归结为如何使用常用工具引用字符串(awk,perl,...).我更喜欢一种解决方案,它不会使引用的字符串不可读.内容store应该或多或少看起来像我在命令行上指定的那样.

由于要引用的参数/字符串可能已经包含任何类型的有效(shell)引用和/或任何类型的(重要)空格,因此无条件地在每个参数周围放置单引号或双引号或存储一个每行参数不起作用.

seh*_*ehe 5

为什么举重?

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

你现在可以

storeargs "some" "weird $1 \`bunch\` of" params >  myparams.txt
storeargs "some" 'weird $1 \`bunch\` of' params >> myparams.txt
cat myparams.txt
Run Code Online (Sandbox Code Playgroud)

产量

some weird\ \ \`bunch\`\ of params
some weird\ \$1\ \\\`bunch\\\`\ of params
Run Code Online (Sandbox Code Playgroud)