user2946809
user2946809

Reputation: 31

Why can't I redirect text to a text file?

I'm writing a bash shell script that has to be run with admin permissions (sudo).

I'm running the following commands

sudo -u $SUDO_USER touch /home/$SUDO_USER/.kde/share/config/kcmfonts > /dev/null
sudo -u $SUDO_USER echo "[General]\ndontChangeAASettings=true\nforceFontDPI=96" >> /home/$SUDO_USER/.kde/share/config/kcmfonts

The first command succeeds and creates the file. However the second command keeps erroring with the following:

cannot create /home/username/.kde/share/config/kcmfonts: Permission denied

I can't understand why this keeps erroring on permissions. I'm running the command as the user who invoked sudo so I should have access to write to this file. The kcmfonts file is created successfully.

Can someone help me out?

Upvotes: 3

Views: 333

Answers (2)

jg3
jg3

Reputation: 513

Consider doing this:

echo "some text" | sudo -u $SUDO_USER tee -a /home/$SUDO_USER/filename

The tee command can assist you with directing the output to the file. tee's -a option is for append (like >>) without it you'll clobber the file (like >).

You don't need to execute the left side with elevated privs (although it is just echo, this is a good thing to form as a habit), you only need the elevated privs for writing to the file. So with this command you're only elevating permissions for tee.

Upvotes: 4

Keith Thompson
Keith Thompson

Reputation: 263257

sudo -u $SUDO_USER echo "some text" >> /home/$SUDO_USER/filename

sudo executes the command echo "some text" as `$SUDO_USER".

But the redirection is done under your account, not under the $SUDO_USER account. Redirection is handled by the shell process, which is yours and is not under the control of sudo.

Try this:

sudo -u $SUDO_USER sh -c 'echo "some text" >> /home/$SUDO_USER/filename'

That way, the sh process will be executed by $SUDO_USER, and that's the process that will handle the redirection (and will write to the output file).

Depending on the complexity of the command, you may need to play some games with escaping quotation marks and other special characters. If that's too complex (which it may well be), you can create a script:

$ cat foo.sh
#!/bin/sh
echo "some text" >> /home/$SUDO_USER/filename
$ sudo -u $SUDO_USER ./foo.sh

Now it's the ./foo.sh command (which executes as /bin/sh ./foo.sh) that will run under the $SUDO_USER account, and it should have permission to write to the output file.

Upvotes: 3

Related Questions