1

I saw this piece of code on another question, but I wasn‘t able to comment on the answer so I‘m asking here.

tr '\n' '\0' < file 1<> file

I‘m interested in the 1<> part, never seen that before and I couldn‘t find anything helpful on google.

2

This was in an answer that Stéphane Chazelas wrote. It is a POSIX shell feature and not specific to bash. It will be mentioned in the manual of your shell, together with the descriptions of the other redirection operators.

The 1<>file opens standard output, file descriptor 1, for both reading and writing and attaches it to the file named file in the current directory.

Before that happens, he has already attached standard input from the same file.

tr will then read from its standard input, from file, and will change all newline characters to nul characters. The output from tr is written back to the same file.

This works as long as the result of the tr command is exactly as long as the original data in file.

If the result of tr is shorter than the original file, you will end up with "old data" at the end of the file:

$ cat file
too many @ here: @@@@
the end
$ tr -s '@' <file 1<>file
$ cat file
too many @ here: @
the end
nd

Note that he can't use > as in

tr '\n' '\0' <file >file

since that would truncate file before tr had a chance to read from it (1<> does not truncate the output file, but it does create it if it does not already exist).

He also can not use >> as in

tr '\n' '\0' <file >>file

as that would append the output from tr at the end of the file and leave the old data in place.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.