Store shell arguments in file while preserving quoting

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.

Answers


Why do the heavy lifting?

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

You can now

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

Output

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

Need Your Help

I am looking for an elegant means of extracting nested data from a MATLAB data structure

arrays matlab struct nested-lists

Using MATLAB, other than the brute force technique of using nested FOR loops, I am curious if there is a more elegant means of extracting the X & Y data from the sample data structure that I have

iOS - access a single sqlite DB from both JavaScript and FMDB

javascript ios sqlite cordova-2.0.0

We've got a problem that only seems to show up on an iOS device, but seems to work fine on the simulator. Here's the problem...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.