- Как создать файл в Linux
- Подготовка
- Создание файла с помощью сенсорной команды
- Создание файла с помощью оператора перенаправления
- Создание файла с помощью команды cat
- Создание файла с помощью команды echo
- Создание файла с использованием Heredoc
- Создание большого файла
- Использование команды dd
- Использование команды fallocate
- Выводы
- Creating and Removing Files and Directories Under Linux
- Creating Files
- Creating Directories
- Removing Files
- Removing Directories
- 4 Ways to Create a Text File in Linux Terminal
- Create file in Linux command line
- 1. Create an empty file using touch command
- 2. Create files using cat command
- 3. Create new file using echo command
- 4. Create a new file using a text editor like Nano or Vim
- How To Quickly Create Files Inside Nested Directories In Linux
- 1. Create multiple directories and files
- 1.1. Create multiple directories using mkdir command
- 1.2. Create multiple files using touch command
- 2. Install terminal-AdvancedNewFile in Linux
- 3. Create files inside nested directories in Linux using terminal-AdvancedNewFile utility
- Conclusion
Как создать файл в 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 из командной строки с помощью различных команд и перенаправления.
Если командная строка вам не подходит, вы можете легко создать пустой текстовый файл, используя контекстное меню в диспетчере файлов.
Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.
Источник
Creating and Removing Files and Directories Under Linux
Here is an absolute beginner post on creating and removing Files and Directories under Linux.
Creating Files
The touch command creates a new empty file.
You can create multiple files with the same command. If the file name or directory name already exists, the touch command updates the modification time and access time to the current date and time. You can use absolute or relative path names on the command line when creating new files.
To create an empty file named file1 in the /tmp directory, enter the following commands:
To create multiple empty files use the touch commands with the file names in one line as shown below.
Creating Directories
The mkdir command creates new directories.
Include the –p option if the directory name includes a path name. The command used with the -p option creates all of the non-existing parent directories that do not yet exist in the path to the new directory. You can use absolute or relative path names on the command line when creating new directories.
For example, create a new directory, named dir1, within the /tmp directory.
You can use the command ‘ls -ld’ to view the created directory.
To create a new directory named dir_in located inside a directory named dir_out, use the mkdir command with the -p option. The dir_out directory does not yet exist.
To create the dir1, dir2, and dir3 directories, enter the mkdir command with all the directory names in one line as shown below.
Removing Files
You can permanently remove files from the directory hierarchy with the rm command.
The rm command is a destructive command if not used with the correct option. The table describes the options that you can use with the rm command when removing files and directories.
Option | Description |
---|---|
-r | Includes the contents of a directory and the contents of all subdirectories when you remove a directory |
-i | Prevents the accidental removal of existing files or directories |
The –r option allows you to remove directories that contain files and subdirectories. The -i option prompts you for confirmation before removing any file.
– A yes response completes the removal of the file.
– A no response aborts the removal of the file.
For example, remove the file named file1 from the /tmp directory.
Lets see an example of using the -i option to delete the files.
Removing Directories
You can use the rm command with the -r option to remove directories that contain files and subdirectories.
For example, remove the dir1 directory and its content by using the rm –r command.
If you do not use the -r option with the rm command while removing directories, the following error message appears:
To interactively remove a directory and its contents, use the –i option along with the rm –r command. For example,
The rmdir command removes empty directories.
For example to remove the empty directory dir3, use the command below.
To remove a directory in which you are currently working in, you must first change to its parent directory.
Источник
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.
Источник
How To Quickly Create Files Inside Nested Directories In Linux
This brief guide explains how to quickly create files inside nested directories using «terminal-AdvancedNewFile» tool in Linux and Unix-like operating systems.
1. Create multiple directories and files
We can create multiple directories and/or a hierarchy of directories (directories within directories) using mkdir directory. And we can create multiple files using touch command.
1.1. Create multiple directories using mkdir command
Usually, we create multiple directories at once using mkdir command like below:
Right? Yes, we do.
And, we create a hierarchy of directories (nested directories) as shown below.
Here, «-p» flag will create the parent directory if it is not created already.
If you want to view the directory creation process (verbose output) as they created, use -v flag like below.
The above commands will create directories recursively inside a non-existent directory(s).
To verify if the directories are created, simply use the ‘tree’ command to view the directory structure.
As you can see, dir1 is the parent directory of all other directories inside it. The directories inside dir1 are called child directories of dir1 and parent directories of the subsequent directories.
To put this in other words, dir1 is the parent directory of all. dir2 is the child directory of dir1 and parent directory of dir3 and so on.
The contents of the new hierarchy of directories can be viewed using ls command like below:
You can also use du command to display the directory tree.
You know now how to easily create multiple directories and hierarchy of directories. Like wise, we can create multiple files at once.
1.2. Create multiple files using touch command
To create multiple files at once using touch command, run:
Similarly, we can create files under existing nested directories using command:
Now dir3 has two items, i.e dir4 and file3.txt. You can verify it using ls command:
Sample output:
Please note that you can’t create files under non-existent directories using touch command. You should first create the directories and then create files.
As you can see in the above examples, creating multiple files and directories isn’t that difficult. We can do it with some one-liner commands as described above.
However, I’d like to introduce yet another simple script called «terminal-AdvancedNewFile» or shortly «ad».
It makes the process of creating multiples files and directories faster and easier than using touch and mkdir commands.
2. Install terminal-AdvancedNewFile in Linux
The terminal-AdvancedNewFile utility is a python script to quickly create folders and files like a pro.
Git clone ‘ad’ repository:
This command clone all contents of ‘ad’ repository in a folder named «terminal-AdvancedNewFile».
Go to that directory and copy the script to your local bin/ folder.
Finally, make it executable using command:
Alternatively, you can install it using Pip package manager like below.
To update it, just run:
Done! It is time to test it.
3. Create files inside nested directories in Linux using terminal-AdvancedNewFile utility
To create a hierarchy of directories using ad, run:
Just use the / (forward slash) after each directory to create any number of nested directories. It’s that simple.
I want to create a file named file5 inside dir5. How to do it? The following command will do!
Did you notice? I didn’t specify any extension to the file5. If you do the same process using mkdir command, it would create a directory called file5 .
But, ad script automatically recognizes it from the file name (i.e. file5) and created the file even if I didn’t specify the extension.
Without ad utility, you will have to create the directory first using mkdir command and then create files using touch command as shown below.
Or, combine the two commands as a single command like below:
Conclusion
In this guide, we learned how to create multiple directories and files using traditional Linux commands namely mkdir and touch .
We also looked at how to create files inside nested directories using a Python script named «terminal-AdvancedNewFile».
Источник