这是当我尝试使用 sudo 将文件中的数据附加到另一个文件时导致“权限被拒绝”的 shell 命令:
sudo cat add_file >> /etc/file
at 的文件/etc/file
归root
(即我)所有,其权限为rw-r--r--
. 我应该root
暂时让它工作还是有解决方法sudo
?
这是当我尝试使用 sudo 将文件中的数据附加到另一个文件时导致“权限被拒绝”的 shell 命令:
sudo cat add_file >> /etc/file
at 的文件/etc/file
归root
(即我)所有,其权限为rw-r--r--
. 我应该root
暂时让它工作还是有解决方法sudo
?
运行bash
为sudo
:
$ sudo bash -c "cat add_file >> /etc/file"
$ whoami;sudo bash -c "whoami";whoami
iiSeymour
root
iiSeymour
尝试这样做:
sudo tee -a /etc/file < add_file
它比运行 bash 或sh -c command
一个有趣的可能性是使用ed
(标准编辑器):
sudo ed -s /etc/file <<< $'r add_file\nwq'
我知道我不会因为这个精彩的答案而获得投票,但我还是想把它包括在这里(因为它很有趣)。完毕!
您正在尝试将命令的结果写入sudo cat add_file
文件 /etc/file. 显然你没有这个权利。
man sudo
给出了这个例子:
To make a usage listing of the directories in the /home partition. Note that this runs the commands in a sub-shell to make the cd and file redirection work. $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"
所以你应该尝试:
sudo sh -c "cat add_file >> /etc/file"
与@gniourf_gniourf答案类似的方法,但使用ex
:
sudo ex +"r in.txt" -cwq out.txt
相当于 vi
/ vim
Ex-mode ( -e
)。
这个就地编辑示例是简单、安全和方便的方法,因为它不使用任何 shell 管道、FIFO 或 shell 变通方法中的 shell。
为了提高脚本性能,请考虑使用静音模式 ( -s
)。
尝试
sudo bash -c 'cat add_file >> /etc/file'
或者
cat add_file | sudo tee -a /etc/file > /dev/null