What does > (greater than) exactly do at the begin

2019-07-11 14:23发布

To empty out a file you can type #> file.txt with a > at the beginning of the command line in bash but what exactly happens here or what is the input of >?

Thank you!

2条回答
小情绪 Triste *
2楼-- · 2019-07-11 14:42

You're stating that you wish to feed the output of nothing (or null) to a file with the name 'file.txt '

Because you're using '>' as opposed to '>>', you're stating that the file should be replaced first if it exists.

查看更多
可以哭但决不认输i
3楼-- · 2019-07-11 14:43

Any redirection at a bash shell is read and implemented by bash. For instance, when you execute # ls > /tmp/ls.out command, bash reads and parses the command and identifies redirection operator (>). Bash opens /tmp/ls.out file in write mode (which truncates the file if it exists). Then bash does the pipe()-dup2()-fork()-exec() sequence to map STDOUT filehandle of ls command to the open file handle to /tmp/ls.out file. This way bash achieves redirection.

In your case again, bash identifies that file.txt is a redirection target and opens it in write mode. The open() call (in write mode) truncates the file.txt file. Then bash does not find any command to execute and does nothing.

In summary, since the shell is opening target file in write mode, the existing file gets truncated. Bash does not do anything special to truncate the file.

查看更多
登录 后发表回答