Skip to content

Instantly share code, notes, and snippets.

@erkiesken
Created May 20, 2016 12:00
Show Gist options
  • Save erkiesken/8e35916617fa9b066facda5adf13d5c4 to your computer and use it in GitHub Desktop.
Save erkiesken/8e35916617fa9b066facda5adf13d5c4 to your computer and use it in GitHub Desktop.
redirecting output of sudo command
# Can;t just do this, no permission for my shell to write that file:
sudo echo "deb https://apt.dockerproject.org/repo debian-jessie main" > /etc/apt/sources.list.d/docker.list
# So wrap it into a shell command:
sudo sh -c 'echo "deb https://apt.dockerproject.org/repo debian-jessie main" > /etc/apt/sources.list.d/docker.list'
@mafonso
Copy link

mafonso commented Jun 2, 2016

That might not do what you wish if accessing ENV variables. The use of tee might be more appropriate as in most cases you want to run the command in the current environment but just elevate privileges to redirect the output.

sudo sh -c 'echo "$USER" > /foo.txt' and echo "$USER" | sudo tee /foo.txt will yield different results

tee will also echo to the console, so to have the same behaviour as > you can redirect to /dev/null
echo "$USER" | sudo tee /foo.txt > /dev/null

If you can not pipe an alternative could be: echo "$USER" > >(sudo tee /foo.txt)

e.g

$ export FOO=bar 
$ echo $FOO
bar
$ sudo sh -c 'echo "$FOO" > /foo.txt'
$ cat /foo.txt

$ echo "$FOO" | sudo tee /foo.txt > /dev/null
$ cat /foo.txt
bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment