Linux 之 touch 命令

touch用来创建文件,用来修改文件的时间戳。
命令格式
touch [选项]... 文件...
命令参数
  • -a 或--time=atime或--time=access或--time=use只更改存取时间。
  • -c 或--no-create不建立任何文档。
  • -d使用指定的日期时间,而非现在的时间。
  • -f此参数将忽略不予处理,仅负责解决BSD版本touch指令的兼容性问题。
  • -m 或--time=mtime或--time=modify只更改变动时间。
  • -r把指定文档或目录的日期时间,统统设成和参考文档或目录的日期时间相同。
  • -t使用指定的日期时间,而非现在的时间。
命令功能
touch命令参数可更改文档或目录的日期时间,包括存取时间和更改时间。
创建不存在的目录
创建一个1.txt文件 > touch 1.txt 同时创建2.txt 3.txt文件 > touch 2.txt 3.txt

将5.txt的Access,Modify时间改成和1.txt一样
> touch -r 1.txt 5.txt > ls -rw-r--r-- 1 root root 0 Feb3 23:17 1.txt -rw-r--r-- 1 root root 0 Feb3 23:17 5.txt

批量创建有规律的文件
创建file1.txt file2.txt .... file10.txt
> touch file{1..10}.txt

创建文件并指定文件的时间戳
> touch -t 202102031111 3.txt > ls -al -rw-r--r-- 1 root root 0 Feb3 11:11 3.txt

将5.txt的时间改成2天前
> ls -al 5.txt -rw-r--r-- 1 root root0 Feb3 23:17 5.txt > touch -d "2 days ago" 5.txt > ls -al 5.txt > ls -rw-r--r-- 1 root root 0 Feb1 23:29 5.txt

只修改1.txtModifyChange的时间
> stat 1.txt File: ‘1.txt’ Size: 5Blocks: 8IO Block: 4096regular file Device: fd01h/64769dInode: 101371574Links: 1 Access: (0644/-rw-r--r--)Uid: (0/root)Gid: (0/root) Access: 2021-02-03 23:39:45.258947600 +0800 Modify: 2021-02-03 23:40:10.462066771 +0800 Change: 2021-02-03 23:40:10.462066771 +0800 Birth: - > touch -m 1.txt > stat 1.txt stat 1.txt File: ‘1.txt’ Size: 5Blocks: 8IO Block: 4096regular file Device: fd01h/64769dInode: 101371574Links: 1 Access: (0644/-rw-r--r--)Uid: (0/root)Gid: (0/root) Access: 2021-02-03 23:39:45.258947600 +0800 Modify: 2021-02-03 23:40:53.068649293 +0800 Change: 2021-02-03 23:40:53.068649293 +0800 Birth: -

为什么linux 创建文件是touch 而不是create
touch — change file access and modification times (BSD) touch — change file timestamps (GNU)

touch的作用本来不是创建文件,而是将指定文件的修改时间设置为当前时间。就是假装“碰”(touch)了一下这个文件,假装文件被“修改”了,于是文件的修改时间就是被设置为当前时间。这带来了一个副作用,就是当touch一个不存在的文件的时候,它会创建这个文件。然后,由于touch已经可以完成创建文件的功能了,就不再需要一个单独的create了。
【Linux 之 touch 命令】原文链接:https://rumenz.com/rumenbiji/linux-touch.html
微信公众号:入门小站

    推荐阅读