如何将变量的值传递给命令的标准输入? [英] How can pass the value of a variable to the standard input of a command?

查看:28
本文介绍了如何将变量的值传递给命令的标准输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应该有点安全的 shell 脚本,即不通过命令参数传递安全数据,最好不使用临时文件.如何将变量传递给命令的标准输入?

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 standard input of a command?

或者,如果不可能,我该如何正确使用临时文件来完成这样的任务?

Or, if it's not possible, how can I correctly use temporary files for such a task?

推荐答案

简单但容易出错:使用 echo

像这样简单的事情就可以解决问题:

Simple, but error-prone: using echo

Something as simple as this will do the trick:

echo "$blah" | my_cmd

请注意,如果 $blah 包含 -n-e-E,这可能无法正常工作> 等;或者如果它包含反斜杠(bash 的 echo 副本默认在没有 -e 的情况下保留文字反斜杠,但会将它们视为转义序列并用相应的字符替换它们,即使没有-e 如果启用了可选的 XSI 扩展.

Do note that this may not work correctly if $blah contains -n, -e, -E etc; or if it contains backslashes (bash's copy of echo preserves literal backslashes in absence of -e by default, but will treat them as escape sequences and replace them with corresponding characters even without -e if optional XSI extensions are enabled).

printf '%s
' "$blah" | my_cmd

这没有上面列出的缺点:所有可能的 C 字符串(不包含 NUL 的字符串)都被原封不动地打印出来.

This does not have the disadvantages listed above: all possible C strings (strings not containing NULs) are printed unchanged.

这篇关于如何将变量的值传递给命令的标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆