What is the difference in using "touch file" and "> file" in creating a new file?
>
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.