What is the difference in using "touch file" and "> file" in creating a new file?
Solution 1:
>
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.
Solution 2:
Here is an interesting comparison:
$ cat redirect.sh touch.sh sed.sh awk.sh cp.sh truncate.sh tee.sh vi.sh
> redirect.txt
touch touch.txt
sed 'w sed.txt' /dev/null
awk 'BEGIN {printf > "awk.txt"}'
cp /dev/null cp.txt
truncate -s0 truncate.txt
tee tee.txt </dev/null
vi -esc 'wq vi.txt'
Result:
$ strace dash redirect.sh | wc -l
387
$ strace dash touch.sh | wc -l
667
$ strace dash sed.sh | wc -l
698
$ strace dash awk.sh | wc -l
714
$ strace dash cp.sh | wc -l
786
$ strace dash truncate.sh | wc -l
1004
$ strace dash tee.sh | wc -l
1103
$ strace dash vi.sh | wc -l
1472