I\'m writing a shell script that should be somewhat secure i.e. does not pass secure data through parameters of commands and preferably does not use temporary files. How can
This robust and portable way has already appeared in comments. It should be a standalone answer.
printf '%s' "$var" | my_cmd
or
printf '%s\n' "$var" | my_cmd
Notes:
echo
, reasons are here: Why is printf better than echo?printf "$var"
is wrong. The first argument is format where various sequences like %s
or \n
are interpreted. To pass the variable right, it must not be interpreted as format.Usually variables don't contain trailing newlines. The former command (with %s
) passes the variable as it is. However tools that work with text may ignore or complain about an incomplete line (see Why should text files end with a newline?). So you may want the latter command (with %s\n
) which appends a newline character to the content of the variable. Non-obvious facts:
<<<"$var" my_cmd
) does append a newline.my_cmd
, even if the variable is empty or undefined.