Ubuntu – the difference in using “touch file” and “> file” in creating a new file

command line

I am new to Linux. When I create a new file .gitignore under current directory using bash, I found out that I can do:

> .gitignore


touch .gitignore

It seems they do the same thing. When I check the manual for touch, it says change timestamp for the current file, but there is no manual for >. So can someone explain what can > do and is there any difference in using these two commands under this context? Thanks.

Best Answer

> is the shell redirection operator. See What's is the difference between ">" and ">>" in shell command? and When should I use < or <() or << and > or >()? It is primarily used to redirect the output of a command to a file. If the file doesn't exist, the shell creates it. If it exists, the shell truncates it (empties it). With just > file, there is no command, so the shell creates a file, but no output is sent to it, so the net effect is the creation of an empty file, or emptying an existing file.

touch is an external command that creates a file, or updates the timestamp, as you already know. With touch, the file contents are not lost, if it exists, unlike with >.

The behaviour of > depends on the shell. In bash, dash, and most shells, > foo will work as you expect. In zsh, by default, > foo works like cat > foo - zsh waits for you type in input.

Related Question