What touch command in linux

touch command in Linux with Examples

The touch command is a standard command used in UNIX/Linux operating system which is used to create, change and modify timestamps of a file. Basically, there are two different commands to create a file in the Linux system which is as follows:

  • cat command: It is used to create the file with content.
  • touch command: It is used to create a file without any content. The file created using touch command is empty. This command can be used when the user doesn’t have data to store at the time of file creation.

Using touch Command

Initially, we are in home directory and this can be checked using the pwd command. Checking the existing files using command ls and then long listing command(ll) is used to gather more details about existing files. As you can see in the below figure there is no existing files.

Touch command Syntax to create a new file: You can create a single file at a time using touch command.

Syntax:

The file which is created can be viewed by ls command and to get more details about the file you can use long listing command ll or ls -l command . Here file with name ‘File1‘ is created using touch command.

Touch command to create multiple files: Touch command can be used to create the multiple numbers of files at the same time. These files would be empty while creation.

Syntax:

Multiple files with name Doc1, Doc2, Doc3 are created at the same time using touch command here.

touch Command Options

Like all other command Touch command have various options. These options are very useful for various purpose.

touch -a: This command is used to change access time only. To change or update the last access or modification times of a file touch -a command is used.

Syntax:

Here touch -a command changes access time of the file named Doc1.

touch -c : This command is used to check whether a file is created or not. If not created then don’t create it. This command avoids creating files.

Syntax:

touch -c-d : This is used to update access and modification time.

Syntax:

touch -m : This is used to change the modification time only. It only updates last modification time.

Syntax:

touch -r : This command is used to use the timestamp of another file. Here Doc2 file is updated with the time stamp of File 1.

Syntax:

touch -t : This is used to create a file using a specified time.

Источник

Использование команды touch в Linux

Как известно, в операционных системах Linux присутствует огромное количество встроенных терминальных команд, выполняющих самые разнообразные действия. Некоторые из них позволяют устанавливать программы, другие предназначены для управления логическими томами и жесткими дисками. Существуют среди них и те, которые созданы для взаимодействия с файлами. Одна из таких команд называется touch, и именно о ней мы и хотим рассказать в рамках данного обучающего материала.

Читайте также:  Connecting to the internet with windows 10

Используем команду touch в Linux

Для использования команды touch в Linux потребуется изучить ее синтаксис и понять принципы ввода. С этим не должно возникнуть никаких проблем, поскольку сама утилита довольно проста, а с доступными опциями можно разобраться буквально за несколько минут. Давайте как раз и начнем с этого.

Синтаксис

Обратим внимание на стандартный вид строки при вводе команды touch. Она выглядит так: touch + [Опции] + Файл . Если же действие нужно осуществить от имени суперпользователя, в начале строки придется добавить sudo, а после ее активации написать пароль, подтверждающий учетную запись. Что касается дополнительных опций, то стоит отметить следующие:

  • ––help и ––version используются редко. Первая опция даст возможность прочесть официальную документацию, а вторая отобразит текущую версию утилиты.
  • -a отвечает за изменение времени доступа к указанному файлу.
  • -m изменяет время модификации.
  • -c определяет, что объект с указанным именем создан не будет.
  • -r позволит использовать время доступа и модификации указанного файла.
  • -t предназначена для изменения даты и времени путем ручного ввода.
  • -d использует дату и время, заданные в виде строки.

Теперь вы знаете абсолютно обо всех доступных опциях рассматриваемой сегодня команды. Давайте перейдем к изучению параметров, чтобы разобраться со всеми основными действиями, выполняемыми при помощи данной утилиты.

Генерация пустых файлов

Для начала разберемся с действием команды touch без применения каких-либо аргументов — так она создает пустой файл размером 0 байт с указанным названием.

    Откройте «Терминал» удобным для вас образом, например, через значок в меню приложений или комбинацию клавиш Ctrl + Alt + T.

После активации этой команды, если она прошла без каких-либо ошибок, появится новая строка для ввода, а в текущем расположении создастся соответствующий объект.

Вы можете добавить несколько файлов одновременно, по очереди написав название каждого, чтобы получилась примерно такая строка: touch testfile1 testfile2 testfile3 .

Имеется одна особенность, которую тоже следует учитывать. Если появилась надобность создать несколько файлов с одинаковым названием, но с разными цифрами в конце, как это было показано выше, проще использовать такой тип написания: touch testfile <1..6>.

Больше команда touch без применения аргументов ничего сделать не способна, поэтому давайте сразу же перейдем к разбору примеров взаимодействия с опциями.

Установка времени последнего доступа

Как вы уже знаете, одна из опций рассматриваемой команды разрешает изменить время доступа к файлу на текущее. Осуществляется это путем ввода всего одной строки которая имеет вид touch -a file , где file — имя необходимого объекта. Количество перечисляемых элементов для одной строки не ограничивается. При этом время последнего изменения не устанавливается, если только в данной строке не дописана дополнительная опция -m, о ней мы и поговорим далее.

Установка времени последнего изменения

По той же аналогии работает и упомянутый выше аргумент -m. Ое переназначает время последнего изменения на текущее, а строка выглядит так: touch -m file . Все внесенные изменения вступают в действие сразу же, а это значит, что вы можете переходить к их проверке или к выполнению других задач, ради которых и вызывалась команда touch с опцией -m.

Запрет на создание объекта

Простая утилита touch иногда позволяет реализовать и сложную цель путем ввода буквально одной строки в консоль. После выполнения команды touch -c file , где file — точное название нужного файла, элемент с указанным именем нельзя будет создать обычному пользователю. Деактивируется эта опция только после того, как привилегированный пользователь создаст пустой объект с таким же названием через эту же команду. Дополнительно ничего не мешает вам создать список из названий, чтобы одновременно установить на них ограничения.

Установка времени доступа и изменений

Приведенные выше опции -a и -m позволяли только изменить параметры файла, установив текущее время, однако имеется возможность задать абсолютно любое время с точностью до секунды. При этом главное — соблюдать правило ввода: [[ВВ]ГГ]ММДДччммм[.сс] , где ВВ — первые две цифры года, ГГ — вторые, ММ — месяц, ДД — дата, чч — часы, мм — минуты, сс — секунды. Необходимая команда получается такой: touch -c -t 01261036 file .

Читайте также:  Как запустить команду с правами администратора windows 10

Если вы заинтересованы в просмотре итогового результата, напишите в консоли ls -l и нажмите на Enter. В списке остается только отыскать необходимый файл и просмотреть, когда он был модифицирован.

Перенос временных меток выбранного файла

Если вы ознакомились с приведенной выше информацией, то знаете, что опция -r разрешит перенести временные метки одного объекта на другой. Осуществляется это через строку: touch -r file1 file2 , где file1 — уже имеющийся файл с определенными временными метками, а file2 — новый объект, к которому они и будут применены.

Создание файла с указанным временем

В конце данного материала отметим, что по умолчанию touch создает файлы с актуальным временем, однако это можно изменить, применив всего одну опцию: touch -t 201912101830.55 file , где 201912101830.55 — точно указанное время на ваш выбор, а file — название того самого объекта или объектов, если они будут представлены в виде списка.

Теперь вы знакомы с командой touch, которая активно используется в Linux для создания файлов. Это могут быть как отдельные тестовые элементы, так и объекты, добавленные для определенных целей. Пользователь уже сам решает, в каком русле применять возможности утилиты. Если вас заинтересовала тема основных команд этой операционной системы, предлагаем изучить представленные далее материалы.

Помимо этой статьи, на сайте еще 12315 инструкций.
Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.

Отблагодарите автора, поделитесь статьей в социальных сетях.

Источник

9 Useful Examples of Touch Command in Linux

Touch command in Linux

Touch command in Linux is used for changing file timestamps however one of the most common usages of touch command includes creating a new empty file.

With the touch command, you can change access, modify and change time of files and folders in Linux. You can update the timestamps or modify them to a date in the past.

The syntax for touch command is quite simple:

What are file timestamps in Linux, again?

I have written about timestamps in Linux in detail in an earlier article. I would recommend reading it for a better and clearer understanding. For the sake of a quick recall, I’ll list the timestamps here:

  • access time – last time when a file was accessed
  • modify time – last time when a file was modified
  • change time – last time when file metadata (file permission, ownership etc) was changed

You can see the timestamps of a file using the stat command in the following manner:

Stat command even shows the inode number of the file.

9 Practical examples of touch command in Linux

Now let’s see how to use the touch command with some simple but useful examples.

1. Create an empty file

As I mentioned earlier, this is the most common use of touch command. All you have to do is to use touch with the file name.

This will create an empty file if the file doesn’t exist.

But what if the file already exists? In that case, it will update all three timestamps of the file to the current time.

2. Create multiple empty files

You can use touch to create more than one empty file as well. Just provide the names of the files you want to create.

If you think it’s tiring to write all filenames, you can auto-generate filenames in this way:

Читайте также:  Hp 1012 driver linux

This will create new-file-1.txt, new-file-2.txt upto new-file-10.txt.

3. Avoid creating a file with touch if it doesn’t exist

Touch will update the timestamps of input file if it exists and will create an empty file if the input file does not exist.

But what if you don’t want touch to create a new empty file? You want it to update the timestamps of the file but if the file doesn’t exist, it should not be created.

You can use the touch command with -c option in such cases:

Remember: Touch will create a new empty file if it doesn’t exist else it will modify the timestamps of the existing file. You can stop the creation of a new file with the -c option.

4. Change all timestamps of a file

If you use touch on an existing file, it will change access, modify and change time of that file.

For example, I have this file named sherlock.txt with the following timestamps:

If I use touch on this command, all timestamps will be changed to the current timestamps.

Note: You should not be bothered with ctime (change time). It’s a system property and cannot/shouldn’t be controlled by the user. Your focus should be on access and modify time.

5. Update only access time of file

You may not always want to change all the timestamps of a file. If you just want to change the access time of a file, you can use the -a option with touch.

6. Update only modify time of file

If you just want to update the modify time of a file to the current timestamp, use the -m option of touch command.

7. Use timestamps of another file

You can also use the timestamps of another file as a reference with the -r option in the following manner:

This will set the access and modify time of the target file same as the access and modify time of the source file.

8. Set specific access and modification time

You might have noticed that in almost all the cases (except the reference file one), the timestamps are changed to the current timestamp.

But you are not bound with that. Touch allows you to set access and modification time to a past or future date. You can use the -t option and a timestamp in the following format:

  • CC – First two digits of a year
  • YY – Second two digits of a year
  • MM – Month of the year (01-12)
  • DD – Day of the month (01-31)
  • hh – Hour of the day (00-23)
  • mm – Minute of the hour (00-59)
  • ss – Seconds (00-59)

In the above case, CC is optional. In fact, CCYY is optional as well, it will take the current year in that case. Similarly, seconds are optional as well, it defaults to 00.

Let me show you an example by changing the timestamp to 12021301 i.e., 12th month, second day, 13th hour and first minute of the current year:

If you try to enter an invalid date, you’ll see an error. You’ll also notice that change time is using the current timestamp, not the same as access and modify. It’s because it’s system property.

You can also use touch command with symbolic links. You just have to use the -h option while dealing with symbolic links. The rest stays the same as the regular files.

I hope you find these touch command examples in Linux helpful. If you have any questions or suggestions, do let me know.

Источник

Оцените статью