xDroid's Blog

12 touch (从新手到菜鸟的Linux教程)

我觉得所有Linux命令里面好像只有touch这个命令是最莫名其妙的;因为它常常被拿来做并非它原本用途的事情。

在 3 关于Shell世界的“Hello World” (从新手到菜鸟的Linux教程) 我们提到过可以用重定向符>>向一个文件的尾端插入一些内容。但是如何新建一个文件呢?

确实可以这样:

wang:~$ echo >> file
wang:~$ ls
Desktop    Downloads         file   Pictures  Templates
Documents  examples.desktop  Music  Public    Videos
wang:~$ cat file

不过在一些不能使用重定向符的特殊情况下(比如find命令的-exec参数),我们怎么办到这一点呢?就是用touch

从字面上看,touch是触摸的意思,怎么和创建文件有关系了呢?不妨先来看一下man的说明:

TOUCH(1) User Commands TOUCH(1)

NAME
touch - change file timestamps

SYNOPSIS
touch [OPTION]… FILE…

DESCRIPTION
Update the access and modification times of each FILE to the current
time.

   A FILE argument that does not exist is created empty, unless -c  or  -h
   is supplied.

看来 touch 原本是用来改变时间戳的;不过既然文件不存在就会创建一个的话,它也可以拿来创建文件用,比如说:

wang:~$ touch new_file
wang:~$ ls
Desktop    Downloads         file   new_file  Public     Videos
Documents  examples.desktop  Music  Pictures  Templates
wang:~$ cat new_file
wang:~$

要注意到 touch 生成的是空文件哦。