Create file with linux command

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.

Читайте также:  Что делать когда windows завис при загрузке обновлений

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.

Источник

Unix Create a File Command

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 5m
  1. Unix cat command
  2. echo or printf command
  3. vi text editor
  4. emacs text editor
  5. joe text editor
  6. Any other console based text editor

Method #1: Creating a file using echo command

Open the Terminal and then type the following command to create a file called demo.txt, enter:

OR create a file with two lines in demo-1.txt file:

To examine the contents of the file you have just created is to type the following command at shell prompt:
cat demo.txt
cat demo-1.txt
Sample outputs:

Fig.01: Examine the contents of the file you’ve just created with cat command.

Method #2: Creating a file using cat command

In this example, create a file named quotes.txt and enter one line of text in it, type the following at the shell prompt:

You need to press the [Enter] or [Return] key. Finally type the text:

Again, press the [Enter] or [Return] key. To stop and save file entry by typing Control+d on a line by itself i.e Press and hold down the Control key and type d . On your screen you will see as follows:
cat > quotes.txt
There are some who question the relevance of space activities in a developing nation.
To us, there is no ambiguity of purpose.
^D

OR

Animated gif 01: Creating a file with cat command

Method #3: Create a text file using vi / vim text editor

vi / vim is a text editor. To create a file called text.txt, type:
$ vi bar.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).

  • 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 do I edit a file just created?

You need to use a text editor such as vi or emacs:
vi filename
Grab mastering the VI editor pdf file for more information on how to use a text editor (see below for link).

Further readings
  • Learn more about vi here : Download mastering the VI editor pdf version.
  • See man pages: ksh(1)

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

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

i want to learn basic unix commands

If you just want an empty file you can do : > filename

You guys rock. This is a life saver. I’ve tacking a UNIX/Linux class on line and i feel lost. Just came across your website and in 10 minutes learned the first week of the online class.

the tutorial on how to is what i think people really need. It’s one thing to show the commands but its great to see exactly how its typed. I always get confused on when and where spaces go.

Now I’m 48 and been around computer for 20+ years but have been tainted when windows.

Very helpful commands
Thanks!

hello
can u plz tell me how can i create a text file in unix?

Источник

Как создать файл в Linux

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

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

Подготовка

Чтобы создать новый файл, вам необходимо иметь права на запись в родительский каталог. В противном случае вы получите сообщение об ошибке в разрешении отказано.

Если вы хотите отобразить содержимое каталога, используйте команду ls .

Создание файла с помощью сенсорной команды

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

Самый простой и запоминающийся способ создания новых пустых файлов — использовать touch команду.

Чтобы создать новый файл, просто запустите touch команду, после которой укажите имя файла, который вы хотите создать:

Если файл file1.txt не существует, приведенная выше команда создаст его, в противном случае она изменит свои временные метки.

Чтобы создать сразу несколько файлов, укажите имена файлов через пробел:

Создание файла с помощью оператора перенаправления

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

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

Это самая короткая команда для создания нового файла в Linux.

Создавая файл с использованием перенаправления, будьте осторожны, чтобы не перезаписать важный существующий файл.

Создание файла с помощью команды cat

Команда cat в основном используется для чтения и объединения файлов, но ее также можно использовать для создания новых файлов.

Чтобы создать новый файл, выполните команду cat, за которой следует оператор перенаправления > и имя файла, который вы хотите создать. Нажмите Enter введите текст и, когда вы закончите, нажмите CRTL+D чтобы сохранить файлы.

Создание файла с помощью команды echo

Команда echo печатает строки, которые передаются в качестве аргументов в стандартный вывод, который можно перенаправить в файл.

Чтобы создать новый файл, запустите команду echo за которой следует текст, который вы хотите напечатать, и используйте оператор перенаправления > чтобы записать вывод в файл, который вы хотите создать.

Если вы хотите создать пустой, просто используйте:

Создание файла с использованием Heredoc

Здесь документ или Heredoc — это тип перенаправления, который позволяет передавать команде несколько строк ввода.

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

Например, чтобы создать новый файл file1.txt вы должны использовать следующий код:

Тело heredoc может содержать переменные, специальные символы и команды.

Создание большого файла

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

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

Команда dd в основном используется для преобразования и копирования файлов.

Чтобы создать файл с именем 1G.test размером 1 ГБ, выполните:

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

fallocate командной строки для выделения реального дискового пространства для файлов.

Следующая команда создаст новый файл с именем 1G.test размером 1 ГБ:

Выводы

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

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

Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.

Источник

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.

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.

Источник

Читайте также:  Как запустить файл run linux
Оцените статью