10

In this line:

tr a A < /etc/hosts | sort -r |pr -d > /etc/hosts 

what would be the expected outcome? I know lowercase 'a' would change to uppercase 'A' but what's next? Would the original file be overwritten since the redirect is to the same file name?

Michael Homer
  • 76,565
tdharrison
  • 101
  • 3
  • You should get a bash: /etc/hosts: Permission denied error (assuming your shell is bash), unless you're running this as root. /etc/hosts is normally writable by root only. Iff you're running this as root (which you really shouldn't), you'd get an empty /etc/hosts as Michael Homer explained. – arielf Feb 26 '18 at 18:39

1 Answers1

17

The expected outcome is a blank /etc/hosts file.

The redirection > /etc/hosts occurs and truncates the file before the programs start running and tr begins to read from the file.

To write the output into /etc/hosts, you could either work with a copy of the file (or move your output file into place afterwards), or use the sponge command from moreutils, which will soak up standard input and write to a file:

tr a A < /etc/hosts | sort -r | pr -d | sponge /etc/hosts

In that case, each "a" in /etc/hosts will be replaced with "A", all lines will be sorted in reverse according to your locale, a blank line will be inserted between each line, and the result will be put into /etc/hosts.


You may also find useful:

Kusalananda
  • 333,661
Michael Homer
  • 76,565