• 运行如下代码为例
    sudo apt-get update

     

  •  第一种方法

    使用管道(上一个命令的 stdout 接到下一个命令的 stdin):

    #!/bin/bash
    echo yourpassword | sudo -S apt-get update

     

  • 第二种方法

    使用文本块输入重定向:

    #!/bin/bash
    sudo -S apt-get update << EOF 
    yourpassword
    EOF
     

    说明:在shell脚本中,通常将EOF与 << 结合使用,表示后续的输入作为子命令或子Shell的输入,直到遇到EOF为止,再返回到主Shell,即将‘你的密码’当做命令的输入

  • -S参数的作用

    使用man命令查询sudo,对参数-S的说明如下:
     

    Write the prompt to the standard error and read the password 
    from the standard inputinstead of using the terminal device. 
    The password must be followed by a newline character.

    可见 加上-S参数 sudo才会从标准输入中读取密码,不加-S参数以上命令将起不到作用

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐