How to pass the value of a variable to the stdin of a command?

后端 未结 9 565
無奈伤痛
無奈伤痛 2020-11-27 14:44

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

9条回答
  •  粉色の甜心
    2020-11-27 14:51

    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:

    • It's better than 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:

      • Here string in Bash (<<<"$var" my_cmd) does append a newline.
      • Any method that appends a newline results in non-empty stdin of my_cmd, even if the variable is empty or undefined.

提交回复
热议问题