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 ?
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 ?
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:
You can do the redirection with:
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.:
This causes 'dd' to be run as root and have it open the file for writing instead of your shell.
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 thesudo
, and not the sudo'ed command (echo). So the priviledges of the redirection hasn't been escalated.