简体   繁体   中英

Why does shell redirection fail when using echo/sudo?

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 ?

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, eg:

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.

您可以使用以下方法进行重定向:

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

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM