Linux write string to file

Open and write data to text file using Bash?

How can I write data to a text file automatically by shell scripting in Linux?

I was able to open the file. However, I don’t know how to write data to it.

12 Answers 12

The short answer:

However, echo doesn’t deal with end of line characters (EOFs) in an ideal way. So, if you’re gonna append more than one line, do it with printf :

The >> and > operators are very useful for redirecting output of commands, they work with multiple other bash commands.

You can redirect the output of a command to a file:

or append to it

If you want to write directly the command is echo ‘text’

I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.

Then cat the file on terminal

This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd’s then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max or /proc/sys/fs/file-max but using any fd above 9 is dangerous as it could conflict with fd’s used by the shell internally. So don’t bother and only use fd’s 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways 🙂

Anyhow, fd’s can be used in a lot of interesting ways.

I like this answer:

but would suggest cat >> FILE.txt if you want just add something to the end of the file without wiping out what is already exists

Moving my comment as an answer, as requested by @lycono

If you need to do this with root privileges, do it this way:

For environments where here documents are unavailable ( Makefile , Dockerfile , etc) you can often use printf for a reasonably legible and efficient solution.

I thought there were a few perfectly fine answers, but no concise summary of all possibilities; thus:

The core principal behind most answers here is redirection. Two are important redirection operators for writing to files:

Redirecting Output:

echo ‘text to completely overwrite contents of myfile’ > myfile

Appending Redirected Output

echo ‘text to add to end of myfile’ >> myfile

Here Documents

Others mentioned, rather than from a fixed input source like echo ‘text’ , you could also interactively write to files via a «Here Document», which are also detailed in the link to the bash manual above. Those answers, e.g.

Читайте также:  Скрипт linux переместить файлы

cat > FILE.txt or cat >> FILE.txt

make use of the same redirection operators, but add another layer via «Here Documents». In the above syntax, you write to the FILE.txt via the output of cat . The writing only takes place after the interactive input is given some specific string, in this case ‘EOF’, but this could be any string, e.g.:

cat > FILE.txt or cat >> FILE.txt

would work just as well. Here Documents also look for various delimiters and other interesting parsing characters, so have a look at the docs for further info on that.

Here Strings

A bit convoluted, and more of an exercise in understanding both redirection and Here Documents syntax, but you could combine Here Document style syntax with standard redirect operators to become a Here String:

Источник

How to write the output into the file in Linux

How do I save terminal output to a file?

A command can receive input from a file and send output to a file.

Writing the output into the file

The syntax is
command > filename
For example, send output of the ls command to file named foo.txt
$ ls > foo.txt
View foo.txt using the cat command:
$ cat foo.txt
Please note that when you type ‘ls > foo.txt’, shell redirects the output of the ls command to a file named foo.txt, replacing the existing contents of the file. In other words, the contents of the file will be overwritten.

Appending the output or data to the file

The syntax is
command >> filename
For example the following will append data:

  • 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

Verify it:
cat /tmp/data.txt

How to save the output of a command to a file in bash using tee command

The tee command read from standard input and write to standard output and files. The syntax is as follows for writing data into the file:
command | tee file.txt
Want to append data? Try
command | tee -a output.txt

Examples

Display output of the date command on screen and save to the file named /tmp/output.txt. If the output.txt already exists, it gets overwritten:
$ date | tee /tmp/output.txt
$ cat /tmp/output.txt
Same as above but append to the given files, do not overwrite file:
$ pwd | tee -a /tmp/test.txt
$ echo «Today is $(date)» | tee -a /tmp/test.txt
$ hostnamectl | tee -a /tmp/test.txt
$ cat /tmp/test.txt

The above commands will append the output to the end of the file, just like the shell >> operator as explained earlier.

I/O redirection summary for bash and POSIX shell

Shell operator Description Overwrite existing file?
command > output.txt Save terminal output (standard output) to a file named output.txt Yes
command >> output.txt Append terminal output (standard output) to a file named output.txt No
command Takes standard input from output.txt file N/A
command 0 Takes standard input from output.txt file N/A
command 1> output.txt Puts standard output to output.txt file Yes
command 1>> output.txt Appends standard output to output.txt No
command 2> output.txt Puts standard error to output.txt Yes
command 2>> output.txt Appends standard error to output.txt file No
command &> output.txt Puts both standard error and output to output.txt Yes
command > output.txt 2>&1 <POSIX> Puts both standard error and output to file named output.txt Yes
command &>> output.txt Appends both standard error and output to file named output.txt No
command >> output.txt 2>&1 <POSIX> Appends both standard error and output to file called output.txt No
command | tee output.txt Puts standard output to output.txt while displaying output on screen Yes
command | tee -a output.txt Appends standard output to output.txt while displaying output on screen No
command |& tee output.txt Puts both standard output and error to output.txt while displaying output on terminal Yes
command 2>&1 | tee output.txt <POSIX> Puts both standard output and error to file named output.txt while displaying output on terminal Yes
command |& tee -a output.txt Append both standard output and error to file called output.txt while displaying output on terminal No
command 2>&1 | tee -a output.txt <POSIX> Append both standard output and error to file named output.txt while displaying output on terminal No
Читайте также:  Объект windows мой компьютер

Conclusion

You learned how to write the output to the file in Linux or Unix-like system when using bash or POSIX shell. We have:

  1. /dev/stdin (standard input) — File descriptor 0 is duplicated.
  2. /dev/stdout (standard output) — File descriptor 1 is duplicated.
  3. /dev/stderr (standard error) — File descriptor 2 is duplicated.

See I/O redirection documentation for more information. We can read bash man page as follows using the man command:
man bash

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

Источник

Bash write to file without echo?

As an exercise, does a method exist to redirect a string to a file without echo? Currently I am using

I know about cat and printf . I was thinking something like

Of course this doesnt work, but maybe a similar command?

9 Answers 9

You can do this with «cat» and a here-document.

One reason for doing this would be to avoid any possibility of a password being visible in the output of ps. However, in bash and most modern shells, «echo» is a built-in command and it won’t show up in ps output, so using something like this is safe (ignoring any issues with storing passwords in files, of course):

I had the problem not being able to send «>» and ended up with echo!

The way to do this in bash is

This is one of the interesting differences between zsh and bash: given an unchained > or >> , zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful — if it were only standard. I tried to use this to send & append my ssh key over ssh to a remote authorized_keys file, but the remote host was bash, of course, and quietly did nothing.

And that’s why you should just use cat .

There are way too many ways to possibly discuss that you probably don’t care about. You can hack of course — strace bash, or do all sorts of black magic running Bash in gdb.

You actually have two completely different examples there. is already writing a string to a file. If anything is acceptable other than printf , echo , and cat , you can use many other commands to behave like cat (sed, awk, tee, etc).

Читайте также:  Windows calculator нагружает процессор

Or hell, depending on how you’ve compiled Bash.

If you want to use only bash strings and redirection, in pure bash, with no hacking, and no loadables, it is not possible. In ksh93 however, it is possible.

Источник

Linux save string to file without ECHO command

I want to save a command to a file (for example I want to save the string «cat /etc/passwd» to a file) but I can’t use the echo command.

How can I create and save string to a file directly without using echo command?

7 Answers 7

You can redirect cat to a file, type the text, and press Control-D when you’re done, like this:

By ^D I mean to press Control-D at the end. The line must be empty. It will not be part of the file, it is just to terminate the input.

Are you avoiding ECHO for security purposes (e.g. you’re using a shared terminal and you don’t want to leave trace in the shell history of what you’ve written inside your files) or you’re just curious for an alternative method?

Simple alternative to echo:

As someone said, redirecting cat is probably the simpler way to go. I’d suggest you to manually type your end-of-file, like this:

Here’s the string you’re asking for, as an example:

You probably don’t want everyone to know you’ve peeked into that file, but if that’s your purpose please notice that wrapping it inside an executable file won’t make it more private, as that lines will be logged anyway.

Security — Avoiding history logs etc..

In modern shell, just try adding a space at the beginning of every command and use freely whatever you want.

Источник

Thread: writing to a file from the command-line

Thread Tools
Display

writing to a file from the command-line

I have created a file called myfile.txt. So could someone tell me how to write something into the file from the command-line please

Re: writing to a file from the command-line

Re: writing to a file from the command-line

$cat some text > myfile.txt

$ cat some text >> myfile.txt .. append to file

Re: writing to a file from the command-line

$cat some text > myfile.txt

$ cat some text >> myfile.txt .. append to file

echo «some text»>>myfile.txt
cat «somefile.txt>>myfile.txt»

If you use only a single more than symbol >, it will delete the file and write ONLY what you asked it to. a double >> adds it onto the end without deleting anything.

cat is for files (It reads the file and outputs it, i.e. cat file.txt gives back the contents of file.txt)
Echo is for plain text.

Re: writing to a file from the command-line

Re: writing to a file from the command-line

Shows just how much of a noob i am. So i shall start from the beginning.

I created a text file called myfile.txt by using: touch myfile.txt
I also created a directory by using: mkdir Mytext
I moved myfile.txt into the Mytext directory by using: mv myfile.txt

/Mytext
I typed ls to make sure that myfile was inside the Mytext directory

Now while i was still in the Mytext directory i typed:
cat «Up hill and over dale»>>myfile.txt (clicked on Enter)

And was rewarded with: No such file or diectory

Would someone please tell me where i am going wrong?

Re: writing to a file from the command-line

I used: echo «Up hill and over dale»>>myfile.txt (clicked on enter)
and the used: cat myfile.txt to view the contents

Thanks for the replies everyone

Источник

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