20

I want to do a simple redirection. When I do

sudo curl <insert link here> > a.txt

I want to take all of the data outputted by the curl into a.txt. However, I keep getting an error saying

a.txt: Permission denied

Would anyone have any idea how to get around this? I've tried looking online by doing

sudo bash -c curl <insert link here> > a.txt

and that displays the same error. Any help would be appreciated! Thanks!

user1871869
  • 3,317
  • 13
  • 56
  • 106

2 Answers2

39

The privilege elevation only applies to the curl process (and, in the second example, the child shell) itself, not to your (parent) shell, and therefore not to the redirection.

One solution is to do the redirection within the child shell itself:

sudo bash -c "curl $LINK >a.txt"

Another, fairly idiomatic option is to use tee:

curl $LINK | sudo tee a.txt >/dev/null

For curl specifically, you can also make the process itself write to the file directly:

sudo curl -o a.txt $LINK
Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
  • Hm, every time I try to do one of the commands, I get an error saying curl: (7) couldn't connect to host. Might you know why? – user1871869 May 17 '13 at 16:12
  • 2
    Curl can't connect to the server. Maybe it's down or there's a firewall or your network settings are screwy or you mistyped the URL.It's not related to the problem you asked about. – Cairnarvon May 17 '13 at 19:57
0

I ran into the same problem and it's because the folder of a.txt isn't writable to you. Either chmod/chown it or put it to a writable folder will solve the problem.

Hope this helps!

janetkuo
  • 2,635
  • 14
  • 17