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
As per Martin's answer, there is a bash feature called Here Strings (which itself is a variant of the more widely supported Here Documents feature).
http://www.gnu.org/software/bash/manual/bashref.html#Here-Strings
3.6.7 Here Strings
A variant of here documents, the format is:
<<< word
The word is expanded and supplied to the command on its standard input.
Note that Here Strings would appear to be bash-only, so, for improved portability, you'd probably be better off with the original Here Documents feature, as per PoltoS's answer:
( cat <<EOF
$variable
EOF
) | cmd
Or, a simpler variant of the above:
(cmd <<EOF
$variable
EOF
)
You can omit (
and )
, unless you want to have this redirected further into other commands.
Try this:
echo "$variable" | command
(cat <<END
$passwd
END
) | command
The cat
is not really needed, but it helps to structure the code better and allows you to use more commands in parentheses as input to your command.
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.I liked Martin's answer, but it has some problems depending on what is in the variable. This
your-command <<< """$your_variable"""
is better if you variable contains " or !
Just do:
printf "$my_var" | my_cmd
If the var doesn't contain spaces then the quotes may be omitted.
If using bash then you may also do:
echo -n "$my_var" | my_cmd
Avoid using echo without -n because it will pipe the vraiable with an added linebreak at the end.