20

From Generate script in bash and save it to location requiring sudo we have this method, which I like:

sudo tee "$OUTFILE" > /dev/null <<'EOF'
foo
bar
EOF

However, I would like to use that approach to append to an existing file $OUTFILE. The above method overwrites existing file $OUTFILE.

MountainX
  • 17,168
  • 59
  • 155
  • 264
  • 2
    always worth reading the manual. `man tee` – Philip Couling Jul 21 '13 at 12:16
  • 3
    @couling-comments like this fail to consider a couple things. First, when I asked the question I was grappling with heredocs, redirection, sudo & tee. For all I knew, the issue could have been related to my usage of heredocs or something else. Second, I was not even sure the tee approach was the right one. Granted, I could have read all the manuals for every element of my proposed solution and all my alternatives. But if everyone did that, we wouldn't need a place like this to ask questions. Finally, I don't think your comment respects Stack Exchange etiquette (although I am not entirely sure) – MountainX Jul 21 '13 at 18:48
  • 1
    firstly this was intended as a polite pointer to which manual was appropriate not a blind "RTFM". That's well within stack exchange etiquette. Secondly it is also good etiquette to explain how to find an answer as well as simply give one. To that end: if a file is being overwritten and that file is only referenced as an argument to a command, I'd start with the manual for that command not read every possible manual for your code. `man sudo` would fairly quickly point you to the fact that tee is a command in it's own right, thus lead you to `man tee`. – Philip Couling Jul 22 '13 at 11:44

3 Answers3

20

You want the -a option to tee which appends rather than overwriting.

jordanm
  • 41,988
  • 9
  • 116
  • 113
5

If you prefer to use cat, then go this route, first passing $OUTFILE as your output's receptacle:

$ OUTFILE=/path/to/restricted_write_access/file
$ sudo out=$OUTFILE sh -c 'cat << EOF >> $out
foo
bar
EOF'
Cbhihe
  • 2,549
  • 2
  • 21
  • 30
  • Disregard my previous comment. I missed the fact that you were using `sudo sh -c`. However, you would need to import `$OUTFILE` into the `sh -c` shell: `sudo sh -c 'cat <>"$1" ...' sh "$OUTFILE"` – Kusalananda Mar 10 '20 at 11:43
  • @Kusalananda. Tx. I had missed that. I only add this very late response for the sake of completion. I realized after the fact that various similar solution are posted, some of them on SE. – Cbhihe Mar 10 '20 at 14:25
1

tee requires you to open up a stream to /dev/null, you can get away doing this with a simple cat

cat <<EOF >> $OUTFILE
foo
bar
EOF

Save your keyboard!

trevorgrayson
  • 229
  • 2
  • 4
  • 13
    Except that this doesn't work with `sudo` (the redirection is performed before elevating permissions, which will fail if your regular user doesn't have permissions to modify `$OUTFILE`). That's why people use `tee` for this purpose instead. – godlygeek Jun 30 '15 at 16:57