New file linux terminal

Как создать файл в терминале

Философия Linux гласит — всё в системе есть файл. Мы ежедневно работаем с файлами, и программы, которые мы выполняем, — тоже файлы. В разных случаях нам может понадобиться создать в системе файлы определённого типа. Если вам интересно, какие типы файлов в Linux можно создать, смотрите отдельную статью.

Конечно, всё очень просто делается с помощью мышки и файлового менеджера. Но если вы дружите с клавиатурой, создать файл через терминал Linux намного быстрее и, как вы увидите, эффективнее. В терминале вы можете не только создавать пустые файлы, но и создавать файл с уже готовым содержимым, файлы определённого размера, и с нужными метаданными.

Как всё это делать, вы узнаете из этой статьи. Мы рассмотрим все доступные средства создания файлов в терминале Linux. Поехали!

1. Редактор nano

Самый распространённый способ создать текстовый файл в Linux — это использовать консольные текстовые редакторы. Например nano. После ввода команды открывается редактор, и вы прописываете нужный текст, например:

files

2. Редактор Vi

Тот же принцип, но программа намного серьёзнее:

files1

Если вы в первый раз столкнулись с vim, то предупрежу — это необычный редактор. Здесь есть два режима: режим вставки и командный. Переключаться между ними можно с помощью кнопки Esc. Для выхода из редактора в командном режиме наберите :q, для сохранения файла — :w. Вообще, Vim — очень полезный инструмент. Чтобы узнать побольше о его возможностях и выучить основы, выполните: vimtutor.

Понятное дело, в этом пункте можно говорить и о других редакторах, в том числе и с графическим интерфейсом. Но мы их опустим и перейдём к другим командам создания файла в Linux.

3. Оператор перенаправления >

Это, наверное, самая короткая команда для создания файла в Linux:

files2

Оператор оболочки для перенаправления вывода позволяет записать вывод любой команды в новый файл. Например, можно подсчитать md5 сумму и создать текстовый файл в Linux с результатом выполнения.

files3

Это рождает ещё несколько способов создания файла в Linux, например, выведем строку в файл с помощью команды echo:

files4

Этот способ часто используется для создания конфигурационных файлов в Linux, так сказать, на лету. Но заметьте, что sudo здесь работать не будет. С правами суперпользователя выполниться echo, а запись файла уже будет выполнять оболочка с правами пользователя, и вы всё равно получите ошибку Access Denied.

Ещё тем же способом можно сделать примитивный текстовый редактор для создания файла. Утилита cat без параметров принимает стандартный ввод, используем это:

files5

После выполнения команды можете вводить любые символы, которые нужно записать в файл, для сохранения нажмите Ctrl+D.

Читайте также:  Linux multiseat на одной видеокарте

А ещё есть утилита printf, и здесь она тоже поддерживает форматирование вывода:

printf «Это %d текстовая строка\n» 1 > файл

files6

Этот способ создать файл в Linux используется довольно часто.

4. Оператор перенаправления вывода >>

Также можно не только перезаписывать файл, а дописывать в него данные, с помощью перенаправления оператора >>. Если файла не существует, будет создан новый, а если существует, то строка запишется в конец.

echo «Это текстовая строка» > файл.txt
$ echo «Это вторая текстовая строка» >> файл.txt

files7

5. Оператор перенаправления 2>

Первые два оператора перенаправления вывода команды в файл использовали стандартный вывод. Но можно создать файл в терминале Ubuntu и перенаправить в него вывод ошибок:

file11

Если команда не выдает ошибок, файл будет пустым.

6. Оператор перенаправления и head

С помощью команды head можно выбрать определённый объем данных, чтобы создать текстовый файл большого размера. Данные можно брать, например, с /dev/urandom. Для примера создадим файл размером 100 мегабайт:

base64 /dev/urandom | head -c 100M > файл

7. Команда cp

Команда cp используется для копирования файлов в Linux. Но с её помощью можно и создать файл. Например, чтобы создать пустой файл, можно просто скопировать /dev/null:

8. touch

Вот мы и подобрались к непосредственному созданию файлов через терминал, для этого в Linux есть специальная утилита touch. Она позволяет создать пустой файл в Linux, при этом указывать дату создания, права доступа и другие метаданные.

Чтобы создать пустой файл Linux, просто наберите:

files8

Можно создать несколько пустых файлов сразу:

Опция -t позволяет установить дату создания. Дата указывается опцией -t в формате YYMMDDHHMM.SS. Если не указать, будет установлена текущая дата. Пример:

touch -t 201601081830.14 файл

Можно использовать дату создания другого файла:

Также можно установить дату последней модификации, с помощью опции -m:

touch -m -t 201601081830.14 файл

Или дату последнего доступа:

touch -a -t 201601081830.14 файл

Чтобы посмотреть, действительно ли задаётся информация, которую вы указали, используйте команду stat:

files9

9. Утилита dd

Это утилита для копирования данных из одного файла в другой. Иногда необходимо создать файл определённого размера в Linux, тогда можно просто создать его на основе /dev/zero или /dev/random, вот так:

dd if=/dev/zero of=~/файл count=20M

files10

Параметр if указывает, откуда брать данные, а of — куда записывать, count — необходимый размер. Ещё можно указать размер блока для записи с помощью bs, чем больше размер блока, тем быстрее будет выполняться копирование.

Создание специальных файлов в Linux

В Linux, кроме выше рассмотренных обычных текстовых и бинарных файлов, существуют ещё и специальные файлы. Это файлы сокетов и туннелей. Их нельзя создать обычными программами, но для этого существуют специальные утилиты, смотрите подробнее в статье, ссылку на которую я дал вверху.

Выводы

Это были все возможные команды для создания файла в Linux. Если вы знаете другие, которые следовало бы добавить в статью — поделитесь в комментариях.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Make a File in Linux from the Command Line – Create a File in the Terminal

Zaira Hira

Zaira Hira

How to Make a File in Linux from the Command Line – Create a File in the Terminal

Managing files from the command line is one of the most common tasks for a Linux user.

Files are created, edited, deleted, and used by many of the background OS processes. Files are also used by regular users to accomplish daily tasks such as taking notes, writing code, or simply duplicating content.

Читайте также:  Linux load library command line

In this article, we will see three methods through which we can create files using the terminal. The three commands that we’ll discuss are touch , cat and echo .

Pre-requisites:

You should have access to the Linux terminal to try out the commands mentioned in this tutorial. You can access the terminal in either of the following ways:

  • Install a Linux distro of your choice on your system.
  • Use WSL (Windows Subsystem for Linux), if you want to use Windows and Linux side by side. Here is a guide to do that.
  • Use Replit which is a browser-based IDE. You can create a Bash project and access the terminal right away.

Method #1: How to Create Files Using the touch Command

The touch command creates empty files. You can use it to create multiple files as well.

Syntax of the touch command:

Examples of the touch command:

Let’s create a single empty file using the syntax provided above.

Next, we’ll create multiple files by providing the file names separated with spaces after the touch command.

touch mod.log messages.log security.log

The above command will create three separate empty files named mod.log , messages.log , and security.log .

Method #2: How to Create Files Using the cat Command

The cat command is most commonly used to view the contents of a file. But you can also use it to create files.

Syntax of the cat command:

This will ask you to enter the text that you can save and exit by pressing ctrl+c .

When I enter the above command, my terminal output looks like this:

zaira@Zaira:~$ cat > sample.txt This is a sample file created using the "cat" command ^C

Note the ^C sign, which corresponds to Ctrl+c and signals to the terminal to save and exit.

Here are the contents of the created file:

zaira@Zaira:~$ more sample.txt This is a sample file created using the "cat" command

Method #3: How to Create Files Using the echo Command

The echo command is used to add and append text to files. It also creates the file if it doesn’t already exist.

Syntax of the echo command:

echo "some text" > sample.txt
echo "some text" >> sample.txt

The difference between > and >> is that > overwrites the file if it exists whereas >> appends to the existing file.

If you would like to follow along with the video tutorial of this article, here is the link:

Conclusion

In this article, we discussed three different methods to create files in the Linux command line. I hope you found this tutorial helpful.

What’s your favorite thing you learned from this tutorial? Let me know on Twitter!

You can read my other posts here.

Источник

Terminal Basics #4: Creating Files in Linux

In this chapter of Linux Terminal Basics series for beginners, learn about creating new files using Linux commands.

Let’s now learn about creating files in the Linux command line. I’ll briefly discuss adding content to the file. However, details on editing text files will be covered later.

Create a new empty file with touch command

Using the touch command is pretty straightforward.

Читайте также:  Linux log accessed files

Switch to your home directory and create a new directory called practice_files and switch to this directory:

mkdir practice_files && cd practice_files

The && is a way to combine two commands. The second command only runs when the first command is executed successfully.

Now, create a new file named new_file:

That’s it. You have just created a new empty file.

List the directory content and check the properties of the file with ls -l command.

The touch command’s original purpose is to ‘touch’ a file and change its timestamp. If the provided file does not exist, it creates a new file with the name.

Create a new file using the echo command

I should have introduced you to the echo command long back. Better late than never. The echo command displays whatever you provide to it. Hence the name echo.

You can use redirection and route the output to a file. And hence creating a new file in the process:

echo "Hello World" >> other_new_file

This way, you create a new file named other_new_file with the text Hello World in it.

Remember, if the provided file already exists, with >> redirection, you add a new line to the file. You can also use > redirection but then it will replace the existing content of the file.

More on redirection can be found in the below tutorial.

Create new files using the cat command

The original purpose of the cat command was to concatenate files. However, it is primarily used for displaying the contents of a file.

It can also be used to create a new file with the option to add content. For that, you can use the same > and >> redirections.

But this one will create a new file and allow you to add some text to it. Adding text is optional. You can exit the cat entering mode by using Ctrl+d or Ctrl+c keys.

Again, the append mode >> adds new text at the end of file content while the clobber mode > replaces the existing content with new.

Use the long listing display with ls -l and notice the timestamps. Now touch the file touch other_new_file . Do you see the difference in the timestamps?

Test your knowledge

You have learned about creating new files. Here are a few simple exercises to practice what you just learned. It includes a little bit of the previous chapters as well.

  • Use the touch command to create three new files named file1, file2 and file3. Hint: You don’t need to run touch three times.
  • Create a directory called files and create a file named my_file in it.
  • Use the cat command to create a file called your_file and add the following text in it «This is your file».
  • Use the echo command to add a new line «This is our file» to your_file.
  • Display all the files in reverse chronological order (refer to chapter 3). Now use the touch command to modify the timestamp of file2 and file3. Now display the content in reverse chronological order again.

That’s pretty fun. You are making good progress. You have learned to create new files in this chapter. Next, you’ll learn about viewing the contents of a file.

Источник

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