Article 56JR2 Preserve quotes using $* redirected to file.

Preserve quotes using $* redirected to file.

by
nicedreams
from LinuxQuestions.org on (#56JR2)
I'm writing a function for saving a command to a file from a script, but it won't preserve the single and double quotes inside of the command.

It does work from the shell if I do while surrounding it with 'single quotes' (simple example):

> echo 'rsync --exclude="/etc"' >> ~/file.txt

But if I do almost the same thing within a bash script it strips the quotes:

> echo "$*" >> ~/file.txt

I'm not talking about "quoting the beginning and end of entire command" I'm needing all the single/double quotes from within the command arguments because a lot of these commands going forward I want to save are long and complex with quoting.

I've tried creating an array hoping would preserve it all, but same results.

> commands=($*)
> echo ${commands[*]} >> ~/file.txt

Tried with $@ but breaks my command into multiple lines instead of single like if using $*

This is the actual code I'm using from my script:

> printf "%s\n" "$*" >> "${notefile}"

and I've tried using ' %q' within printf, but it adds a bunch of \backslashes\ all over the line of code still missing the single/double quotes.

I've tried '"$*"' (single quotes) since the single quotes work if I do the same thing from the shell itself, but it echo's the actual "$*" into the file and not the command. If I use single quotes around the array '${commands[*]' it puts the actual array ${commands[*]} in the file and not the command itself.latest?d=yIl2AUoC8zA latest?i=-sdPGCwN85g:vXc-Sa6HMD4:F7zBnMy latest?i=-sdPGCwN85g:vXc-Sa6HMD4:V_sGLiP latest?d=qj6IDK7rITs latest?i=-sdPGCwN85g:vXc-Sa6HMD4:gIN9vFw-sdPGCwN85g
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments