Create new files in linux

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

Философия 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.

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

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

files6

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

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

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

Читайте также:  Linux show process threads

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.

Источник

4 Ways to Create New File in Linux

Linux based operating systems are known for their users’ heavy use of command line for performing not only complicated automation but also the most trivial of tasks. However, with the steady growth of Linux distributions in the home desktop market, the onus is on the developers to make the graphical interface as lay user friendly as possible.

Today, we will see various ways to perform a simple and trivial task; creating a new file, in Linux using the command line as well as the GUI.

Create File using Touch Command

The touch command in Linux is used to create an empty file and the syntax for creating an empty file is as easy as:

To create multiple files at once, pass multiple file names as arguments:

$ touch sample_file1 sample_file2 sample_file3

Create New File in Linux

The touch command will throw an error if any of the files already exist.

Читайте также:  Лучшие загрузочные диски linux

You can also create the file in another directory by specifying the full path to the directory location.

$ touch ~/Downloads/sample_file1 sample_file5 ~/Documents/sample_file6

Create File in Different Directory

Create File Using Vim and Nano Editors

Vim is a very popular text editor in Linux distributions. Although the command line utility nano is the one available by default, users generally prefer Vim.

Install Vim in Debian and its derived distributions by running:

In RedHat and its derived distributions, install Vim with Yum:

Creating a new file is quite easy using text editors. You can create an empty file by creating a new file for writing and save it without writing anything to the file.

The following syntaxes can be used to create a new file using Vim and Nano respectively:

$ vim new_filename $ nano new_filename

Once the editors open with ‘new_filename‘, users can now write to the file if needed. If writing to file is done, or if the file is to be left empty, do the following to save the file:

Create New File Using Editors

  • In Vim, press the ‘Escape‘ key, type ‘:wq’, and hit Enter to save the file and exit.
  • In Nano, simply press Ctrl + O and hit Enter to save the file. Press Ctrl + X to exit.

Create File Using Redirection Operator

A redirection operator is an operator used in the Linux command line to write output to a file or to read input from a file.

We use the former of these two operators (‘>’) to create a new file with output from a command. For example, to write the output of command ls to a new file, run:

$ ls > sample_newfile $ cat sample_newfile

Write Command Output to File

To create an empty file using this, simple echo command and empty string and redirect it.

Create File Using Redirect Operator

Create File Using File Manager

Lastly, we will see how to create a new file from the GUI. Open Nautilus either by running the command ‘nautilus’, from the left-hand side dock or from the Applications menu, depending on your Linux distribution.

Nautilus File Manager

Go to the folder you want to create the new file in. For example, let’s create a new file in the folder ‘Documents’.

Documents Directory

Right-click on the empty space in the folder display and click on ‘New Document’ -> ‘Empty Document’.

Create New Empty Document

Note: In newer versions of Ubuntu, the option ‘New Document’ might be missing. To fix this simply run the following:

$ touch ~/Templates/Empty\ Document

Right-click on the new file, click ‘Rename’, and enter a new name for the file.

Rename New Empty Document New Empty Document

Conclusion

We learned about multiple ways to create a new file in Linux. There are obviously, even more ways to create a new file, and every individual application usually has the ability to create a new file of its respective format. Eg. Image editors export files to image formats like JPEG and PNG, audio editors to MP3, M4A, etc.

Let us know in the comments below how you go about creating a new file in your Linux system!

Источник

4 Ways to Create a Text File in Linux Terminal

In this Linux beginner series, you’ll learn various methods to create a file in Linux terminal.

In this Linux beginner series, you’ll learn various methods to create a text file in Linux terminal.

If you have used the desktop oriented operating system such as Windows, creating file is a piece of cake. You right click in the file explorer and you would find the option of creating new file.

Читайте также:  Линукс архив tar gz установить

Things won’t look the same when you are in a command line environment. There is no right click option here. So how do you create a file in Linux then? Let me show you that.

Create file in Linux command line

There are various ways of creating a new file in Linux terminal. I’ll show you the commands one by one. I am using Ubuntu here but creating files in Ubuntu terminal is the same as any other Linux distribution.

1. Create an empty file using touch command

One of the biggest usages of the touch command in Linux is to create a new empty file. The syntax is super simple.

If the file doesn’t exist already, it will create a new empty file. If a file with the same name exists already, it will update the timestamps of the file.

2. Create files using cat command

Another popular way of creating new file is by using the cat command in Linux. The cat command is mostly used for viewing the content of a file but you can use it to create new file as well.

You can write some new text at this time if you want but that’s not necessary. To save and exit, use Ctrl+D terminal shortcut.

If the file with that name already exists and you write new text in it using the cat command, the new lines will be appended at the end of the file.

3. Create new file using echo command

The main use of the echo command is to simply repeat (echo) what you type on the screen. But if you use the redirection with echo, you can create a new file.

To create a new file using echo you can use something like this:

echo "This is a sample text" > filename.txt

The newly created filename.txt file will have the following text: This is a sample text. You can view the file in Linux using cat or other viewing commands.

You are not obliged to put a sample text with echo. You can create an (almost) empty file using the echo command like this:

This will create a new file with just one empty line. You can check the number of lines with wc command.

4. Create a new file using a text editor like Nano or Vim

The last method in this series is the use of a text editor. A terminal-based text editor such as Emacs, Vim or Nano can surely be used for creating a new file in Linux.

Before you use these text editors, you should make sure that you know the basics such as saving an existing from the editor. Unlike the GUI tools, using Ctrl+S in the terminal won’t save the file. It could, in fact, send your terminal into a seemingly frozen state from which you recover using Ctrl+Q.

Let’s say you are going to use Vim editor. Make sure that you are aware of the basic vim commands, and then open a new file with it like this:

What’s your favorite command?

So, I just shared 4 different ways of creating a file in Linux. Personally, I prefer using touch for creating empty file and Vim if I have to edit the file. On a related note, you may want to learn about the file command in Linux that is helpful in determining the actual type of the file.

Which command do you prefer here? Please share your views in the comment section below.

Источник

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