5 ms·
It would also be useful in cases when the file must be written with root privileges (but the shell is run as a normal user) Now you have to use `tee` for that,
by alerighi 5y ago
It would also be useful in cases when the file must be written with root privileges (but the shell is run as a normal user)
Now you have to use `tee` for that, that is fine but if you don't want to echo the file back to the terminal you have to do
command | sudo tee file > /dev/null
with this you can simply do
command | sudo sponge file
- leni536 5y agoCan't you just use `cat`?
- ben0x539 5y agoYou cannot use `sudo cat` to open a file with root privileges, because `sudo cat > foo` means "open file foo with your current privileges, then run `sudo cat` passing the file to it", and the whole root thing only happens after you already tried and failed to open the file. I seem to get this wrong roughly once a week.
- gorgoiler 5y ago… | sudo tee foo
- readme 5y agosudo sh -c "cat > file"
- deleted 5y ago[deleted]
- icedchai 5y agoI knew a person who would give something like this as a sysadmin / devops interview question. It was framed as "'sudo cat >/etc/foo' is giving a permission denied error! what's wrong?" Usually the interview candidate would go off on a tangent...
- HellsMaddy 5y agoCat won’t write the file. If you mean `command | sudo cat > file.txt`, that won’t work because the redirection is still happening in the non-root shell. You could do `command | sudo sh -c "cat > file.txt"` but that’s rather verbose.
- jaden 5y agoI thought the same thing. What's wrong with this approach? cat myfile.txt | awk '{do_stuff()}' | sort -u | column --table > new-myfile.txt
- HellsMaddy 5y agocat is doing nothing useful here. Your command is equivalent to awk '{do_stuff()}' myfile.txt | sort -u | column --table > new-myfile.txt The only thing you’ve changed is that you’re sending the output to a new file. That’s fine, but it’s what sponge is avoiding.