Linux每日一篇 - 31 - touch
Linux文件时间戳管理神器!掌握touch命令,轻松创建和修改文件时间,让文件管理更灵活!
touch命令是什么?
touch命令是Linux中用于创建空文件或更新文件时间戳的工具。它可以创建新文件,也可以修改现有文件的访问时间(atime)和修改时间(mtime)。
基本用法
# 创建空文件
touch filename
# 创建多个空文件
touch file1 file2 file3
# 更新文件的访问时间和修改时间为当前时间
touch existing_file
# 只更新访问时间
touch -a existing_file
# 只更新修改时间
touch -m existing_file
# 设置文件时间为指定时间
touch -d "2023-12-25 10:30:00" filename
# 使用参考文件的时间戳
touch -r reference_file target_file
# 设置特定时间戳
touch -t 202312251030.00 filename
实用技巧
# 创建带时间戳的文件
touch "file_$(date +%Y%m%d_%H%M%S).txt"
# 批量创建文件
touch {1..10}.txt
# 创建隐藏文件
touch .hidden_file
# 设置文件为特定日期
touch -d "last Friday" filename
touch -d "tomorrow" filename
touch -d "1 year ago" filename
# 仅创建文件(如果不存在)
touch -c not_existing_file # 如果文件不存在则不创建
# 创建文件并立即写入内容
touch log.txt && echo "Log started at $(date)" > log.txt
# 更新多个文件的时间戳
touch *.log
# 设置文件时间戳为变量指定的时间
target_time="2023-12-25 15:30:00"
touch -d "$target_time" filename
# 使用touch作为标记文件
touch /tmp/build_complete # 标记构建完成
常用场景
# 在脚本中创建临时文件
touch /tmp/script_temp_file
# 创建日志文件(但不写入内容)
touch /var/log/myapp.log
# 更新配置文件的时间戳以触发某些服务重启
touch /etc/myapp/config.conf
# 批量更新文件时间
touch -m *.html # 更新所有HTML文件的修改时间
# 创建占位符文件
touch /home/user/important_todo.txt
# 创建多个测试文件
touch test_{a..z}.txt
# 将文件时间设置为系统编译时间
touch -d "$(stat -c %y Makefile)" source.c
# 创建锁文件
touch /var/lock/myapp.lock
# 创建多个目录的占位文件
for dir in /path/to/project/*; do
touch "$dir/.gitkeep"
done
# 确保文件存在(用于脚本)
touch -c /path/to/optional_file # 只在文件存在时更新时间戳
高级用法
# 创建文件并设置特定时间戳
touch -d "2023-01-01 00:00:00" old_file.txt
# 使用相对时间
touch -d "now + 1 hour" upcoming_event.txt
touch -d "now - 1 day" yesterday_file.txt
# 复制时间戳
touch -r source_file target_file
# 同时创建文件并设置时间
touch new_file.txt && touch -d "2023-06-15" new_file.txt
# 在脚本中用于检测文件更新
touch -d "2023-01-01" reference_time
if [ newer_file -nt reference_time ]; then
echo "newer_file is newer than reference"
fi
# 批量处理文件时间戳
find /path/to/directory -name "*.txt" -exec touch {} \;
# 创建多个不同扩展名的空文件
touch index.{html,css,js}
# 在Makefile中的应用(防止某些操作)
# 在Makefile中,touch可以用来更新目标文件的时间戳,防止重复构建
注意事项
# 1. touch命令的-d选项支持很多日期格式
touch -d "Dec 25 2023"
touch -d "2023-12-25"
touch -d "25/12/2023 15:30"
touch -d "next Monday"
# 2. 使用-c选项可防止创建新文件(只更新现有文件的时间)
touch -c filename # 只更新时间,不存在则不创建
# 3. -a和-m选项可以单独更新访问或修改时间
touch -a filename # 只更新访问时间
touch -m filename # 只更新修改时间
# 4. -h选项用于符号链接(如果系统支持)
touch -h symlink_name # 更新符号链接本身的时间戳
关于我
全平台同名”汪多多是只猫”,专注分享实用技术教程,让你的IT学习之路更轻松!
关注我,每天一个Linux命令,轻松入门Linux系统!