shell中针对sudo需要密码时的处理

发布时间 2023-05-28 13:14:08作者: 砚台是黑的

方式一

# shell 脚本中自动为 sudo 输入密码
echo 123456 | sudo -S apt update

-S, --stdin
Write the prompt to the standard error and read the password
from the standard input instead of using the terminal device.
将提示写入标准错误,从标准输入读取密码,而不是使用终端设备。

方式二

# 记录在shell脚本中使用sudo echo x > 时,抛Permission denied错误
# 利用管道和 tee 命令,该命令可以从标准输入中读入信息并将其写入标准输出或文件中,
# 具体用法如下:
echo a |sudo tee 1.txt
echo a |sudo tee -a 1.txt   // -a 是追加的意思,等同于 >>
tee 命令很好用,它从管道接受信息,一边向屏幕输出,一边向文件写入。