How to Create Files and Directories in Linux using "touch" and "mkdir" Commands

You can create new files and directories within the directory hierarchy using the touch and mkdir commands. The touch command creates a new, empty file, and the mkdir command creates a new directory.

Creating Empty Files

You can use the touch command to create an empty file. You can create multiple files on the same command line. If the file name or directory name already exists, the touch command updates the modification time and access time to the current date and time. The syntax for the touch command is:

$ touch filename

You can use absolute or relative path names on the command line when creating new files. To create an empty file named space in the dir3 directory, perform the touch command.

$ pwd
/export/home/user1
$ cd dir3
$ ls
planets

$ touch space
$ ls
planets  space

To create three empty files named moon, sun, and cosmos in the dir3 directory, perform the touch command.

$ touch moon sun cosmos
$ ls
cosmos   moon     planets  space    sun
$

Creating Directories

You can use the mkdir command with a directory_name to create directories. If the directory_name includes a path name, use the mkdir command with the -p option. The command used with the -p option creates all of the non-existing parent directories that do not yet exist in the path to the new directory. The syntax for the mkdir command includes:

$ mkdir directory_name
$ mkdir -p directory_names

You can use absolute or relative path names on the command line when creating new directories. To createa new directory, named Reports, within the user1 directory, use the mkdir command.

$ cd
$ pwd
/export/home/user1

$ mkdir Reports
$ ls -ld Reports
drwxr-xr-x 2 user1 staff 512 Mar 14 16:24 Reports

To create a new directory named empty located inside a directory named newdir, perform the mkdir command with the -p option. The newdir directory does not yet exist.

$ cd
$ pwd
/export/home/user1
$ ls
brands      dir10       dir5        file1       file3       letters
dante       dir2        feathers    file.2      file4       Reports
dante_1     dir3        feathers_6  file2       fruit       tutor.vi
dir1        dir4        file.1      file.3      fruit2

$ mkdir -p newdir/empty
$ ls newdir
empty

To create a Weekly directory in the Reports directory, perform the mkdir command.

$ mkdir Reports/Weekly
$ ls Reports
Weekly

To create the dir1, dir2, and dir3 directories in the Weekly directory, perform the mkdir command.

$ cd Reports/Weekly

$ mkdir dir1 dir2 dir3
$ ls -F
dir1/ dir2/ dir3/