First, note that
echo $@ > file.txt
can fail in several ways. Shellcheck identifies one problem (missing quotes on $@
). See the accepted, and excellent, answer to Why is printf better than echo? for others.
Second, as others have pointed out, there is no practical way for a Bash program to know exactly how parameters were specified on the command line. For instance, for all of these invocations
prog \"
prog "\""
prog '"'
the code in prog
will see a $1
value that consists of one double-quote character. Any quoting characters that are used in the invocation of prog
are removed by the quote removal part of the shell expansions done by the parent shell process.
Normally that doesn't matter. If variables or parameters contain values that would need to be quoted when entered as literals (e.g. "\""
) they can be used safely, including passing them as parameters to other programs, by quoting uses of the variable or parameter (e.g. "$1"
, "$@"
, "$x"
).
There is a problem with variables or parameters that require quoting when entered literally if you need to write them in a way that they can be reused as shell input (e.g. by using eval
or source
/.
). Bash supports the %q
format specification to the printf
builtin to handle this situation. It's not clear what the OP is trying to do, but one possible solution to the question is:
if (( $# > 0 )) ; then
printf -v quoted_params '%q ' "$@" # Add all parameters to 'quoted_params'
printf '%s\n' "${quoted_params% }" # Remove trailing space when printing
fi >file.txt
That creates an empty 'file.txt' when no positional parameters are provided. The code would need to be changed if that is not what is required.