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 I pass a variable to the stdin of a command? Or, if it's not possible, how to correctly use temporary files for such task?
问题:
回答1:
Something as simple as:
echo "$blah" | my_cmd
回答2:
Passing a value on stdin is as simple as:
your-command <<< "$your_variable"
Always make sure you put quotes around variable expressions!
回答3:
Note that the 'echo "$var" | command
operations mean that standard input is limited to the line(s) echoed. If you also want the terminal to be connected, then you'll need to be fancier:
{ echo "$var"; cat - ; } | command
( echo "$var"; cat - ) | command
This means that the first line(s) will be the contents of $var
but the rest will come from cat
reading its standard input. If the command does not do anything too fancy (try to turn on command line editing, or run like vim
does) then it will be fine. Otherwise, you need to get really fancy - I think expect
or one of its derivatives is likely to be appropriate.
The command line notations are practically identical - but the second semi-colon is necessary with the braces whereas it is not with parentheses.
回答4:
(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.
回答5:
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 !
回答6:
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.
回答7:
Try this:
echo "$variable" | command
回答8:
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.