Linux 创建文件和目录

点击访问 Linux 命令大全 >>

本章节将介绍在 Linux 系统中,怎样通过命令行创建文件和目录。

mkdir 建立目录

mkdir 命令可以一次建立一个或几个目录。下面的命令一次性在用户主目录下面创建 data1 和 data2 目录,如下:

[root@localhost ~]# mkdir data1 data2
[root@localhost ~]# ll
总用量 12
-rw-------. 1 root root 1259 7月  12 19:20 anaconda-ks.cfg
drwxr-xr-x. 2 root root    6 7月  28 11:51 data1
drwxr-xr-x. 2 root root    6 7月  28 11:51 data2
-rw-r--r--. 1 root root   14 7月  19 06:00 test1.txt
-rw-r--r--. 1 root root   14 7月  19 06:00 test2.txt

也可以使用绝对路径新建目录。如下:

[root@localhost ~]# mkdir ~/data3

注意:上面的 ~ 表示当前主目录。

在创建多层目录时,如果中间层的目录不存在,则创建目录失败。如下:

[root@localhost ~]# mkdir ~/tmp/data
mkdir: 无法创建目录"/root/tmp/data": 没有那个文件或目录

上面“mkdir ~/tmp/data”命令执行失败,因为 tmp 目录不存在。如果我们想创建多层目录,则可以使用 mkdir 的 -p 选项。如下:

[root@localhost ~]# mkdir -p ~/tmp/data
[root@localhost ~]# ll ~/tmp
总用量 0
drwxr-xr-x. 2 root root 6 7月  28 17:40 data

上面例子中,mkdir 将县创建 tmp 目录,然后创建 data 目录。

touch 建立一个空文件

touch 命令的使用非常简单,只需要在后面跟上一个文件名作为参数。如下:

[root@localhost ~]# touch hello.txt
[root@localhost ~]# ll hello.txt
-rw-r--r--. 1 root root 0 7月  28 17:43 hello.txt

上面命令将会在当前目录下面创建一个 hello.txt 空文件(即不包含任何内容的文件)。当某些应用程序因为缺少文件而无法启动,这时需要创建一个空文件“骗过”程序。

touch 命令的另一个用途是更新一个文件的建立日期和时间。如下:

## 查看 anaconda-ks.cfg 文件的创建日期,7月12日
[root@localhost ~]# ll anaconda-ks.cfg
-rw-------. 1 root root 1259 7月  12 19:20 anaconda-ks.cfg

## 更新文件日期
[root@localhost ~]# touch anaconda-ks.cfg

## 文件日期被更新为 7月28日
[root@localhost ~]# ll anaconda-ks.cfg
-rw-------. 1 root root 1259 7月  28 17:48 anaconda-ks.cfg

touch 命令的这个功能在自动备份和整理文件时非常有用,这使得程序可以决定哪些文件已经被备份或整理过了。

echo 创建文件

除了使用 touch 命令创建空文件外,echo 命令也可以非常快速的创建一个文件。如下:

[root@localhost ~]# echo hello > hello_echo.txt
[root@localhost ~]# ll hello_echo.txt
-rw-r--r--. 1 root root 6 7月  28 17:53 hello_echo.txt

上面实例,使用 echo 命令快速将“hello”内容写入到 hello_echo.txt 文件。

利用 echo 命令创建空文件。如下:

[root@localhost ~]# echo > empty.txt
[root@localhost ~]# ll empty.txt
-rw-r--r--. 1 root root 1 7月  28 17:54 empty.txt
[root@localhost ~]# cat empty.txt

[root@localhost ~]#
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号