Linux touch command usage examples
Command definition
The touch
command in Linux is primarily used to create empty files or update the timestamps of existing files. When you execute touch
followed by a file name, it will create a new, empty file if it does not already exist. If the file does exist, touch
will update its last access and modification times to the current time without modifying its content.
Usage examples
-
Create a new empty file: You can create a new file simply by typing
touch filename.txt
. This will create an empty file namedfilename.txt
in the current directory.
bash touch filename.txt
-
Update the timestamp of an existing file: If you have a file and want to update its access and modification times, you can use
touch filename.txt
. This will not change the file's content but will refresh its timestamps.
bash touch filename.txt
-
Create multiple files at once: You can create multiple files in one command by listing them, for example,
touch file1.txt file2.txt file3.txt
. This will create three empty files.
bash touch file1.txt file2.txt file3.txt
-
Create a file in a specific directory: To create a file in a specific directory, you can specify the path, like
touch myfolder/filename.txt
. This command createsfilename.txt
insidemyfolder
.
bash touch myfolder/filename.txt
-
Change the timestamp of multiple files: To update the timestamps of multiple files at once, use
touch file1.txt file2.txt
. This will refresh the timestamps of both files.
bash touch file1.txt file2.txt
-
Create a file with a specific timestamp: You can set a specific timestamp using the
-t
option, liketouch -t 202301010101 filename.txt
, which sets the timestamp to January 1, 2023, at 01:01 AM.
bash touch -t 202301010101 filename.txt
-
Create a file with the current date and time: By simply executing
touch filename.txt
, you can create or update a file with the current date and time as its timestamp.
bash touch filename.txt
-
Use with wildcard to create multiple files: You can use wildcards to create multiple files, such as
touch file{1..5}.txt
, which createsfile1.txt
,file2.txt
,file3.txt
,file4.txt
, andfile5.txt
.
bash touch file{1..5}.txt
-
Check if a file exists: After using
touch
, you can check if a file was created or updated by usingls -l filename.txt
to view the file details, including its timestamp.
bash ls -l filename.txt
-
Create a file in a non-existent directory: If you try to run
touch myfolder/filename.txt
withoutmyfolder
existing, it will return an error. You must create the directory first withmkdir myfolder
.
bash mkdir myfolder && touch myfolder/filename.txt