使用 sudo 命令时,重定向标准输出的两种方法

sunls24 于 2023-01-10 发布 浏览量

错误的写法:

sudo cat >/etc/sysctl.d/bbr.conf <<EOF
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
EOF

此写法看似很合理,但执行的时候会报 Permission denied 这是因为输出重定向(例如>)由shell执行,而不是由cat执行,sudo命令只对cat命令进行了提权,shell在进行重定向的时候会报权限不足的错误。

两种解决方法

对 shell 进行提权

sudo bash -c 'cat >/etc/sysctl.d/bbr.conf' <<EOF
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
EOF

使用 tee 命令

cat <<EOF|sudo tee /etc/sysctl.d/bbr.conf >/dev/null
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
EOF

参考链接