Ben
Ben

Reputation: 344

What does > (greater than) exactly do at the beginning of a command line

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!

Upvotes: 2

Views: 1461

Answers (2)

Prasanna
Prasanna

Reputation: 1274

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.

Upvotes: 2

Gov
Gov

Reputation: 375

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.

Upvotes: 0

Related Questions