Why does shell redirection fail when using echo/su

2019-08-19 14:40发布

问题:

I have a simple script which is behaving un-expectedly.

path='/usr/local/bin/new_script'

content='#!/bin/bash\nls'

sudo echo -e "$content" > "$path"

Raises Error:

bash: /usr/local/bin/new_script: Permission denied

What am I doing wrong ?

回答1:

You can do the redirection with:

sudo sh -c "echo -e '$content' > $path"


回答2:

You don't have write access to either the file /usr/local/bin/new_script or the directory /usr/local/bin

Executing the echo command with sudo doesn't help, as echo just writes to whatever file stdout points to. The problem is that the shell opens the file you're attempting to redirect to, which is still running as a regular user.

A solution would be to make sure that the process that ends up opening and writing the file is run as root, e.g.:

echo -e "$content" | sudo dd of="$file"

This causes 'dd' to be run as root and have it open the file for writing instead of your shell.



回答3:

The redirection is handled by the current user, rather than as root. So, unless the current user has write permissions to $path, the redirection may fail.

You can get around this limitation with tee. For example:

# echo as current user; tee as root
echo -e "$content" | sudo tee "$path"


回答4:

You probably don't have permission to write to /usr/local/bin/. You are using sudo, but the file redirection (>) is being applied to the output of the sudo, and not the sudo'ed command (echo). So the priviledges of the redirection hasn't been escalated.