Wednesday, 21 February 2018

linux - What does “” exactly mean in “echo temp.txt”?


Non existing file


$ ls file_not_exists.txt
ls: cannot access file_not_exists.txt: No such file or directory
$ echo <> file_not_exists.txt

$ ls file_not_exists.txt
file_not_exists.txt
$ cat file_not_exists.txt
$

File with content


$ cat temp.txt 
asdf
$ echo temp.txt
temp.txt
$ echo <> temp.txt

$ cat temp.txt
asdf

If the file does not exist, echo <> file_not_exists.txt will create a new file. So I think > works (redirecting the empty output into a newly created file). But if there is something in the file (like temp.txt), why it is not emptied by echo <> temp.txt?



Answer



From the Advanced Bash Scripting Guide


[j]<>filename
# Open file "filename" for reading and writing,
#+ and assign file descriptor "j" to it.
# If "filename" does not exist, create it.
# If file descriptor "j" is not specified, default to fd 0, stdin.
#
# An application of this is writing at a specified place in a file.
echo 1234567890 > File # Write string to "File".
exec 3<> File # Open "File" and assign fd 3 to it.
read -n 4 <&3 # Read only 4 characters.
echo -n . >&3 # Write a decimal point there.
exec 3>&- # Close fd 3.
cat File # ==> 1234.67890
# Random access, by golly.

So,


echo <> temp.txt

Will create temp.txt if it does not exist, and print an empty line. That is all. It is equivalent to:


touch temp.txt && echo



Note, most programs will not expect the STDIN file descriptor (0) to be open for writing, so in most cases, the following will be roughly equivalent:


command <> file
command 0<> file
touch file && command < file

And since most programs will not expect STDOUT to be open for reading, the following are usually roughly equivalent:


command 1<> file
command > file

And for STDERR:


command 2<> file
command &2> file

No comments:

Post a Comment

Where does Skype save my contact&#39;s avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...