touch 命令用于創建空文件,也可以更改 Unix 和 Linux 系統上現有文件時間戳。這里所說的更改時間戳意味著更新文件和目錄的訪問以及修改時間。
讓我們來看看 touch 命令的語法和選項:
語法:
# touch {選項} {文件}
touch 命令中使用的選項:

在這篇文章中,我們將介紹 Linux 中 9 個有用的 touch 命令示例。
示例:1 使用 touch 創建一個空文件
要在 Linux 系統上使用 touch 命令創建空文件,鍵入 touch ,然后輸入文件名。如下所示:
[root@linuxtechi ~]# touch devops.txt[root@linuxtechi ~]# ls -l devops.txt-rw-r--r--. 1 root root 0 Mar 29 22:39 devops.txt
示例:2 使用 touch 創建批量空文件
可能會出現一些情況,我們必須為某些測試創建大量空文件,這可以使用 touch 命令輕松實現:
[root@linuxtechi ~]# touch sysadm-{1..20}.txt在上面的例子中,我們創建了 20 個名為 sysadm-1.txt 到 sysadm-20.txt 的空文件,你可以根據需要更改名稱和數字。
示例:3 改變/更新文件和目錄的訪問時間
假設我們想要改變名為 devops.txt 文件的訪問時間,在 touch 命令中使用 -a 選項,然后輸入文件名。如下所示:
[root@linuxtechi ~]# touch -a devops.txt
現在使用 stat 命令驗證文件的訪問時間是否已更新:
[root@linuxtechi ~]# stat devops.txt File: 'devops.txt' Size: 0 Blocks: 0 IO Block: 4096 regular empty fileDevice: fd00h/64768d Inode: 67324178 Links: 1Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)Context: unconfined_u:object_r:admin_home_t:s0Access: 2018-03-29 23:03:10.902000000 -0400Modify: 2018-03-29 22:39:29.365000000 -0400Change: 2018-03-29 23:03:10.902000000 -0400 Birth: -
改變目錄的訪問時間:
假設我們在 /mnt 目錄下有一個 nfsshare 文件夾,讓我們用下面的命令改變這個文件夾的訪問時間:
[root@linuxtechi ~]# touch -m /mnt/nfsshare/[root@linuxtechi ~]# stat /mnt/nfsshare/ File: '/mnt/nfsshare/' Size: 6 Blocks: 0 IO Block: 4096 directoryDevice: fd00h/64768d Inode: 2258 Links: 2Access: (0755/drwxr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root)Context: unconfined_u:object_r:mnt_t:s0Access: 2018-03-29 23:34:38.095000000 -0400Modify: 2018-03-03 10:42:45.194000000 -0500Change: 2018-03-29 23:34:38.095000000 -0400 Birth: -
示例:4 更改訪問時間而不用創建新文件
在某些情況下,如果文件存在,我們希望更改文件的訪問時間,并避免創建文件。在 touch 命令中使用 -c 選項即可,如果文件存在,那么我們可以改變文件的訪問時間,如果不存在,我們也可不會創建它。
[root@linuxtechi ~]# touch -c sysadm-20.txt[root@linuxtechi ~]# touch -c winadm-20.txt[root@linuxtechi ~]# ls -l winadm-20.txtls: cannot access winadm-20.txt: No such file or directory
示例:5 更改文件和目錄的修改時間
在 touch 命令中使用 -m 選項,我們可以更改文件和目錄的修改時間。
新聞熱點
疑難解答