Creating empty file 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.

Источник

How to create an empty file from command line

How can I create an empty file from the command line?

6 Answers 6

Use the touch command:

Will also create an empty file. If the file does already exist, it will be truncated (emptied). To keep the file contents, use >> for appending as in:

Even if the file exists, the contents will be untouched.

Читайте также:  Intel celeron e3300 windows 10

Edit: If you don’t have any content to type, this one is faster:

Note. : is the command here. It is not part of the prompt.

the exact way there is also another way

The difference is file1.ext will be zero bytes and file2.ext would be one byte. You can check this by

Using vim editor you can also create an empty file.

creates an empty file, if your version of echo supports the -n switch.

Or you could use printf

In general, creating any regular 1 file on Linux involves open(2) , openat(2) , and creat(2) system calls (and specifically with O_CREAT flags). That means if you call any command-line utility that does these system calls, you can create a new empty file.

Most commonly new filename is created with something like this:

  • touch /tmp/new_file
  • : > /tmp/new_file
  • true > /tmp/new_file
  • > /tmp/new_file ( bash shell only )

touch is a standalone utility. Its original purpose is to update the access and modification time of a file, however if the file does not exist — it will be created. Note also that a filename — is treated specially, so if you do want to create a file that is named literally — , you’ll have to enclose that into single or double quotes.

By contrast, > is a shell redirection operator for stdout stream. The > operator specifically calls the openat() system call with O_WRONLY|O_CREAT|O_TRUNC flags. That means, if the filename does not exist — it will be created, and if it does — the data will be truncated (and therefore gone, so > should be used with care). In most shells nowadays true or : is a built-in , so doing : > /tmp/new_file is going to be more efficient, although marginally compared to touch /tmp/new_file .

But of course it does not stop there. As mentioned, anything that can perform open() , openat() and, create() syscalls will create a file. Hence, we can do:

  • true|dd of=/tmp/newfile
  • truncate —size 0 /tmp/new_filename.txt
  • cp /dev/null /tmp/null_file
  • true|tee /tmp/some_other_file
  • mktemp or tempfile ( for creating temporary files that do not need to exist between reboots !)

Of course, all the above mentioned utilities do not exclusively create files. But they perform the necessary syscall and that allows us to adapt the commands.

Of course, at the level of programming or scripting we may want to create a file as well, especially for efficiency purposes (because calling external commands such as touch from a Perl script or Python will require additional resources).

We can make it shorter with this:

1 Other types of files such as hard/soft links,character or block special devices, directory,named pipes, or sockets require entirely different syscalls.

Источник

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

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

Порывшись на Linux форумах, обнаружил, что вариантов несколько. Предлагаю на выбор 11 способов.

Способ 1

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

Способ 2

cat — утилита UNIX, выводящая последовательно указанные файлы (или устройства), таким образом, объединяя их в единый поток. Если вместо имени файла указывается «-», то читается стандартный ввод.

Способ 3

tail — утилита в UNIX, выводящая несколько (по умолчанию 10) последних строк из файла.

Способ 4

date — утилита Unix для работы с системными часами. Выводит текущую дату и время в различных форматах и позволяет устанавливать системное время.

Способ 5

dd — программа Unix, предназначенная как для копирования, так и для конвертации файлов.

Способ 6

Vim — свободный режимный текстовый редактор, созданный на основе более старого vi. Ныне это один из мощнейших текстовых редакторов с полной свободой настройки и автоматизации, и созданным благодаря этому расширениям и надстройкам.

Способ 7

cp — команда Unix в составе GNU Coreutils, предназначенная для копирования файлов из одного в другие каталоги (возможно, с другой файловой системой). Исходный файл остаётся неизменным, имя созданного файла может быть таким же, как у исходного, или измениться.

Способ 8

echo — команда Unix, предназначенная для отображения строки текста. Команда echo — выводит текст (выводит текст на стандартное устройство вывода).

Способ 9

Способ 10

Способ 11

Способ 12

Самый короткий из способов, любезно предоставленный пользователем stam .

Источник

Empty a file while in use in linux

I’m trying to empty a file in linux while in use, it’s a log file so it is continuosly written. Right now I’ve used:

but all of this produce an empty file with a newline character (or strange character that I can see as ^@^@^@^@^@^@^@^@^@^@^@^.. on vi ) and I have to remove manually with vi and dd the first line and then save.

If I don’t use vi adn dd I’m not able to manipulate file with grep but I need an automatic procedure that i can write in a shell script.

6 Answers 6

This should be enough to empty a file:

However, the other methods you said you tried should also work. If you’re seeing weird characters, then they are being written to the file by something else — most probably whatever process is logging there.

Читайте также:  Необходимо обновить installer mac os

What’s going on is fairly simple: you are emptying out the file.

Why is it full of ^@ s, then, you ask? Well, in a very real sense, it is not. It does not contain those weird characters. It has a «hole».

The program that is writing to the file is writing a file that was opened with O_WRONLY (or perhaps O_RDWR ) but not O_APPEND . This program has written, say, 65536 bytes into the file at the point when you empty out the file with cp /dev/null filename or : > filename or some similar command.

Now the program goes to write another chunk of data (say, 4096 or 8192 bytes). Where will that data be written? The answer is: «at the current seek offset on the underlying file descriptor». If the program used O_APPEND the write would be, in effect, preceded by an lseek call that did a «seek to current end-of-file, i.e., current length of file». When you truncate the file that «current end of file» would become zero (the file becoming empty) so the seek would move the write offset to position 0 and the write would go there. But the program did not use O_APPEND , so there is no pre- write «reposition» operation, and the data bytes are written at the current offset (which, again, we’ve claimed to be 65536 above).

You now have a file that has no data in byte offsets 0 through 65535 inclusive, followed by some data in byte offsets 65536 through 73727 (assuming the write writes 8192 bytes). That «missing» data is the «hole» in the file. When some other program goes to read the file, the OS pretends there is data there: all-zero-byte data.

If the program doing the write operations does not do them on block boundaries, the OS will in fact allocate some extra data (to fit the write into whole blocks) and zero it out. Those zero bytes are not part of the «hole» (they’re real zero bytes in the file) but to ordinary programs that do not peek behind the curtain at the Wizard of Oz, the «hole» zero-bytes and the «non-hole» zero bytes are indistinguishable.

What you need to do is to modify the program to use O_APPEND , or to use library routines like syslog that know how to cooperate with log-rotation operations, or perhaps both.

[Edit to add: not sure why this suddenly showed up on the front page and I answered a question from 2011. ]

Источник

Vasanth Blog

The easier way to learn Linux

How to Create an empty file in Linux?

Methods to create a file in UNIX/LINUX:

Linux/UNIX considers everything as a file. Whenever you start working on Linux/UNIX box you have to deal with different file-types.

There are three popular methods available to create a empty file.

Method:1

By using the “touch” command we can create a empty file ..

Note: The syntax to run the UNIX commands is

options: It modify the way in which a command works.

Arguments: It could be a file or directory name as you wish

Note: You must type space between command,options and file or directory name else you will get syntax error message on your screen after execution of the command.

syntax to create a file is:

Task: Create a file inside the parent / directory

#touch /myfile

The file has been created successfully inside the path /…

To get the details of this file you have to use the command “ls” with -l option.

Note : The syntax to run the UNIX commands is

options : It modify the way in which a command works.

Arguments : It could be a file or directory name as you wish

Note: You must type space between command,options and file or directory name else you will get syntax error message on your screen after execution of the command.

#ls -l /myfile

#ls /myfile

With option or without option you can call the ls program to list view the file/dir properties,but it will give you the full details of a file or dir once you add -l option with the “ls” command .

-l option will give you the information’s like:

1.Type of the file

2.Default permission for the file/directory

3.The link count for the file/directory.

4.Owner of the file/directory

5.Group ownership for a file/drectory

6.Size of the file or directory

7.Date and time creation of the file/directory

With out -l option it would display only the file or directory name you mention with the “ls” command.So i recommend you to use -l option always with the “ls” command to fetch the details.

Let me show this with an practical example

In the above example if you can see with out the -l option it displayed only the file name but with the -l option the “ls” command fetches all the details of the file.

Method:2

By using the command called “cat” we can also create an empty file.This command allows you to add the content to the file while you create

Читайте также:  Где находиться windows syswow64

Let me show you the example

The same syntax once again we are going to use here…

#cat >

Task : Create a file inside the / directory

To create a file here we use the notation > with the “cat” command…

#cat >

#cat > /testfile

Here once you hit the enter button the cat program waits for the input to be sent to the file(testfile) after typing the content you can save the content to the file by pressing control+d from your keyboard.

Note: Before insert the content press control+d to save the file .

METHOD :3

Another method to create the file is by using the editor called “vi”(called as visual editor)

In the above first two methods we have seen how to create the files and how to add the content to the empty file,Now what would happen if i use method 1 and method 2 to edit the file? is it possible to edit the file content with touch and cat command,the answer is NO ..It will not allow you to edit the file content ,”cat” command allows only you to append the content or overwrite the file content .

If you need to edit the file content i prefer to use the editor called “VI”.The editor is installed in every UNIX system by default.

Note: An improved version of vi editor is vim,but most Linux system have vi editor installed.

I will explain you in detail about the vi editor in our upcoming topics.

So to create a file by using the vi editor

#vi

#vi /samplefile

IMPORTANT:

Touch command features:

Your manager requested you to modify the date and time of some important files in your directory as a administrator what you would do?

Is it possible for you to modify the date and time of the existing file without disturbing the file content?

YES you can do it …

touch program has some special features

1.which is used to update the access date and modification date of the file.

2.Touch avoids opening,saving and closing the files instead it simply updates the date associated with the file

Note: Mostly administrators use the touch command to modify the access information of the files.

Let me show you with some practical example..here we go…….

1.Check the date and time of your server first:

#date

2.Create a file and add some content

#cat > /test

3.Check the properties of the file

#ls -l /test

4.After 60 second (as you wish you can mention the time) create a file with the same name once again by using touch command

#date

#touch /test

5.Now check the properties of the file

#ls -l /test

From the output you will find the date and time modified to the latest one with out changing the content of the file

6.To read the content of the file

#cat /test

Note that the content of the file still remains the same with out it gets overwrite with empty one.

HOW TO APPEND THE CONTENT TO THE EXISTING FILE:

Now let me show you how to add the content to the file and how to append the content to the existing file without overwrite.

Its very easy to add and append the content to the file

To add the content to the empty file

#cat >/samplefile

Don’t forgot to save the file content by pressing control+d

To confirm whether the content has been added run the following command:

#cat /samplefile

(Here it will display the content which you have entered)

Now the file samplefile is having some content …..my task is to add some more content to this file without overwrite with the new content.I should read both the previous as well the new content after saving the file.

1.Run the command to read the content

#cat /samplefile

2.Append some more content to this file without overwrite

#cat >>/samplefile

(After adding the content press control+d to save)

Note: To append the content to the existing file we have to use the notation >>

3.Run the command once again to read the content

#cat /samplefile

(The output it will show both the old content as well the new content )

The point to remember is use >> notation to add the content to the existing file (which is having some content already inside the file)

Let me show this with some real time example:

Note : Remember here if you use > notation instead of the >> the file content gets overwrite with the new content

If you found this article useful, Kindly Subscribe here👉🏿👉🏿 Click this link to Subscribe

Источник

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