sudo generally only invokes one command with additional arguments, so if you want to do the following, you will get “Permission denied” as normal user:
sudo echo 'new-setting-something' >> /etc/some.conf
You can read it as:
sudo_the_command >> /etc/some.conf
The sudo will invokes /bin/echo, not the Bash built-in command since the invocation is by executable, not via shell. So it runs the command as root and your current shell as normal user gets the output and redirect to the file, where you do not have the permission to write.
There are a few ways to resolve it:
1 -s (shell) option
- -s [command]
- The -s (shell) option runs the shell specified by the SHELL environment variable if it is set or the shell as specified in the password database. If a command is specified, it is passed to the shell for execution via the shell’s -c option. If no command is specified, an interactive shell is executed.
This option enables invoking the command with the SHELL, commonly /bin/bash, but we do not specify a command. Because it still only accepts a single command, not a script. If you run without a command, it starts a shell, kind of doing sudo su.
If you feed with standard input, e.g.
echo "echo 'new-setting-something' >> /etc/some.conf" | sudo -s
This would do the trick, you can use Here Strings to simplify:
sudo -s <<< "echo 'new-setting-something' >> /etc/some.conf"
2 In shell, manually
Another way is to invoke the shell as the command:
sudo sh -c "echo 'new-setting-something' >> /etc/some.conf"
The shell sh is the command, -c and the next string are the two arguments that sudo passes to sh.
You can do this if you want, same thing as using -s:
sudo sh <<< "echo 'new-setting-something' >> /etc/some.conf"
sh interprets whatever comes from standard input, which is the script.
3 tee
Executing tee with sudo as redirection:
echo 'new-setting-something' | sudo tee -a /etc/some.conf
This has a benefit to echo to screen at the same time of appending to the file. Note that in this case, echo doesn’t need to be run as root, but some situation may require root, so it may become:
sudo command-root-only | sudo tee -a /etc/some.conf
4 Wrapped in script
Of course, you can wrap entire thing in a script and run it as the command with sudo, but I don’t think many people would like to do so unless it’s something you run every day.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.