Creating file linux command

4 Ways to Create a Text 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.

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 empty file using echo you can use something like this:

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.

Читайте также:  Не работает планшет после обновления windows

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.

Источник

7 Ways to Create a File in Linux Terminal

In this tutorial, I will show you how to create a file from a Linux terminal. There are many text editors like (vim, nano, vi) and many commands like (cat, echo, printf, touch) to create a file in the Linux operating system via command line. Here will explain the following linux tools.

1) Create a file with touch command

We will use touch command with any extension to create file, this command will create an empty file touch.txt in your current directory as an example below.

To see the file type command below.

2) Create a file with cat command

We will use cat command to create file, this command will create an empty file cat.txt in your current directory as an example below, but you must add text in the file.

Add the text below.

To save the file hit Ctrl + d , and to see the file type command below.

To open the file, we will use cat command to open it.

3) Create a file with echo command

We will use echo command to create file, this command will create a file echo.txt in your current directory as an example below, but you should add text in the line command.

To see the file,type command below.

To open the file, we will use cat command to open it.

4) Create a file with printf command

We will use printf command to create file, this command will create a file printf.txt in your current directory as an example below, but you should add text in the line command.

To see the file type command below.

To open the file, we will use cat command to open it.

5) Create a file with nano text editor

To create a file using nano text editor, first install it, after that type command below and the text editor will be opened to adding text.

Add the text below.

To save the file type Ctrl + x and type y , to see the file type command below.

To open the file, We will use nano command to open it.

6) Create a file with vi text editor

To create a file using vi text editor, type command below and the text editor will open the file, but you can’t add any text before converting it to insert mode by typing i character.

Add the text below.

To save the file and exit hit Esc after that :wq , To see the file type command below.

To open the file, we will use vi command to open it.

7) Create a file with vim text editor

To create a file using vim text editor, type command below and the text editor will open the file, but you can’t add any text before converting it to insert mode by typing i character.

Add the text below.

To save the file and exit hit Esc after that :wq , to see the file type command below.

To open the file, we will use vim command to open it.

Conclusion

In this tutorial, we learned the different ways to create a file from Linux terminal. Hope you enjoyed reading and please leave your comments in the below comment section.

Источник

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

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

Читайте также:  Узнайте разрядность системы 32 или 64 windows

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

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

1. Редактор nano

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

2. Редактор Vi

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7. Команда cp

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

cp /dev/null файл

8. touch

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

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

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

touch файл1 файл2

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

touch -t 201601081830.14 файл

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

touch -r шаблон файл

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

touch -m -t 201601081830.14 файл

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

touch -a -t 201601081830.14 файл

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

9. Утилита dd

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

dd if=/dev/zero of=

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

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

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

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

Выводы

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

Источник

How to create a file in Linux using the bash shell terminal

I am a new Linux system user. How do I create a file in Linux using the bash shell terminal? What is the fastest and easiest way to create a file in a Linux terminal?

Introduction – A file is nothing but a container in a Linux based system for storing information. For example, music stored in a file named foo.mp4. Similarly, my cat’s picture stored in kitten.jpg and so on. This page shows various methods to create a file in Linux using the terminal window.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash shell/terminal on Linux
Est. reading time 3 minutes

How to create a file in Linux from terminal window?

  1. Create an empty text file named foo.txt:
    touch foo.bar
    OR
    > foo.bar
  2. Make a text file on Linux:
    cat > filename.txt
  3. Add data and press CTRL + D to save the filename.txt when using cat on Linux
  4. Run shell command:
    echo ‘This is a test’ > data.txt
  5. Append text to existing file in Linux:
    echo ‘yet another line’ >> data.txt

Let us see some examples for creating a text files on Linux operating systems.

How to create a text file using the cat command

To create a text file named sales.txt, type the following command and then press [Enter] key:
cat > sales.txt
Now type your lines of text. For example:

When done and you need to save and exit, press Ctrl + D to return to the bash shell prompt. To view file use cat or more command/less command:
cat sales.txt
more sales.txt

How to create a file in Linux from terminal window

How to create an empty text file using the touch command

Simply type any one of the following command:
> data.txt
OR
touch test.txt
Verify that empty files are created with the help of ls command:
ls -l data.txt test.txt

Creating a file in Linux using the echo or printf

Let us create a file called quote1.txt using echo command, enter:
echo «While I thought that I was learning how to live, I have been learning how to die.» > quote1.txt
OR use the printf command printf ‘Study nature, love nature, stay close to nature. It will never fail you.\n’ > quote2.txt

Appending data

Use the the >> instead of > to append data to existing file and to avoid overwriting files. The syntax is:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How to create a file in Linux using joe text editor

JOE is text editor. To create a file called delta.txt, type:
joe -help delta.txt
You will see help menu on screen. Next type something. To save the file and leave joe, by typing ^KX (press CTRL+K+X).

How to create a text file in Linux using vi / vim text editor

The vi / vim is another text editor. To create a file called purchase.txt, type:
vi purchase.txt
OR
vim purchase.txt
Press i to insert new text. To save the file and leave vi, type ESC + : + x (press ESC key, type : followed by x and [enter] key).

Conclusion

You learned various methods that allow you to create text files in a Linux or Unix/macOS terminal window quickly.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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