在 Linux 中创建文件有多种方法,以下是最常用的几种方式,按使用场景分类:
touch(最常用)用于创建一个空文件,或更新文件的时间戳。
touch filename
示例:
touch test.txt
创建多个文件:
touch a.txt b.txt c.txt
>(适合创建并写入)创建新文件(若已存在会清空内容):
> filename
示例:
> hello.txt
立即写入内容:
echo "Hello World" > hello.txt
echo创建文件并写入内容:
echo "内容" > filename
示例:
echo "This is a test" > test.txt
追加内容(不覆盖):
echo "new line" >> test.txt
cat + 重定向(交互式)cat > filename
输入内容后按 Ctrl + D 保存。
适合编辑复杂内容:
vim filename
nano filename
printf更精确控制格式:
printf "line1\nline2\n" > test.txt
dd(创建指定大小文件)dd if=/dev/zero of=test.dat bs=1M count=10
创建 10MB 空文件。
文件名以 . 开头即可:
touch .hiddenfile
touchecho / catvim / nano如果你有特定需求(如脚本中创建、批量创建、指定权限),可以告诉我,我可以进一步说明。