Skip to content
Advertisement

what alternative methods for sudo echo without bash -c

I must run the echo in the script my.sh with sudo because permission. I do not want to execute the script with sudo my.sh. I do not want to use bash -c "..." because escaping.

Are there no other solutions?

my.sh

#!/usr/bin/bash
>/file.tmp 
echo '
a="S T"
z=abc
'

Advertisement

Answer

The problem you are encountering here is that the output redirection >/file.tmp has to happen with elevated privileges. This means that you either have to launch the script as it is with sudo my.sh, or perform the redirection in a way that gives it elevated privileges. It is not enough to run sudo echo because only echo would have elevated privileges, but the output redirection would run as your non-root user because it is a shell builtin feature, not an external command.

There is a standard tool called tee that can help with this. This method is commonly used when running curl to fetch data that needs to be fed to root, such as installing debian apt repository configurations and signing keys.

$ whoami
dho
$ whoami | sudo tee whoami.txt >/dev/null
$ ls -la whoami.txt
-rw-r--r-- 1 root root 4 2022-06-03T09:08:22 whoami.txt

So you can see that I launched whoami with my own user, but the file ended up being written with root permissions because tee, which replaces the output redirection from your original example, was launched as sudo tee.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement