Article Title: echo and sudo. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
As we all know, using echo and command redirection is a quick way to write information to a file. This article describes how to use echo and sudo commands to write information to files that only the system administrator has the permission to operate.
For example, if you want to write random content to the test. asc file, you can:
$Echo "Information">Test. Asc # Or $Echo "Information">Test. Asc |
Next, if you set the test. asc permission to only the root user, you can perform write operations:
$ Sudo chown root. rootTest. Asc |
Then, we use sudo and echo commands to write information to the test. asc file after the permission is modified again:
$ SudoEcho "Another line of information">Test. Asc -Bash:Test. Asc: Permission denied |
At this time, we can see that bash refuses to do so, saying that the permission is not enough. This is because the redirection symbols ">" and ">" are also bash commands. We only use sudo to grant root permissions to echo commands, but do not allow ">" and ">" commands to have root permissions, so bash will think that neither of these two commands is like test. the permission to write information to asc files.
There are two ways to solve this problem. The first is to use the "sh-c" command, which allows bash to execute a string as a complete command, so that the sudo impact can be extended to the entire command. The usage is as follows:
$ Sudo sh-c'Echo"Another line of information"> Test. asc' |
Another method is to use the pipeline and tee commands, which can read information from the standard input and write it into the standard output or file. The specific usage is as follows:
$Echo "Article 3"| Sudo tee-Test. Asc |
Note that the "-a" option of the tee command serves the same purpose as the ">" command. If this option is removed, the role of the tee command is equivalent to the ">" command.