Linux save string to file

How to save terminal output to a file under Linux/Unix

H ow do I save the terminal output to a file when using BASH/KSH/CSH/TCSH under Linux, macOS, *BSD or Unix-like operating systems?

Yes, we can save command output by redirecting it to a file. The standard streams for input, output, and error are as follows (also known as file descriptors):

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux, macOS, or Unix
Est. reading time 3 minutes
  1. stdin (numeric value 0) – Keyboard
  2. stdout (numeric value 1) – Screen/display
  3. stderr (numeric value 2) – Screen/display
  • Redirect stdout/stderr to a file
  • Redirect stdout to a stderr OR redirect stderr to a stdout
  • To redirect stderr and stdout to a file
  • We can redirect stderr and stdout to stdout too
  • And finally you can redirect stderr and stdout to stderr

How to save terminal output to a file

By default, the command sends outputs to stdout and can be redirected to the file using the following syntax:
command > filename.txt
For example, save the date command output to a file named mydate.txt, run:
date > mydate.txt
To view file contains use the cat command:
cat mydate.txt

Feed data to our commands (input redirection)

We can read input from a file using the following simple syntax and the file must already exist:
command

  • 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

Append output to a file

If the filename.txt/mydate.txt (file) already exists, it will get overwritten. To append output, run:
command >> filename.txt
echo «——————» >> mydate.txt
ls -l /etc/resolv.conf >> mydate.txt
Verify it:
cat mydate.txt

Please note that the file such as mydate.txt is overwritten unless the bash noclobber option is set using the set command. For example, turn off noclobber option:
set -o noclobber
echo «some data» > mydata.txt
Sample outputs:

We can turn on noclobber option as follows:
set +o noclobber
echo «foo bar» > mydata.txt

How to redirect stderr to a file

The syntax is as follows:
command &> file.txt
command &>> file.txt
OR
command 2> file.txt
command 2>> file.txt
Above works with bash and other modern shell. For POSIX version try:
command >output.txt 2>&1
command >>output.txt 2>&1
In this example, send the find command errors to a file named err.log:
find / -iname «*.conf» &>err.log
## OR ##
find / -iname «*.conf» 2>err.log
## POSIX version ##
find . -iname «*.conf» >err.log 2>&1
Verify it:
cat err.log
Sample outputs:

How to suppress error messages

Use the following syntax:
command 2>&-
find . -iname «*.txt» 2>&-
We can also redirect error messages (stderr) to standard output (stdout), run:
command 2>&1
echo «foo» 2>&1
kill $target_pid 2>&1 > /dev/null

How to redirect both stdout and stderr to a file

The syntax is as follows to redirect both stdout and stderr to a file:
command 2>&1 | tee output.txt
For example:
find . -iname «*.txt» 2>&1 | tee cmd.log
cat cmd.log
To append text to end of file use the following syntx:
find . -iname «*.conf» 2>&1 | tee -a cmd.log
cat cmd.log

How to combine redirections

The following command example simply combines input and output redirection. The file resume.txt is checked for spelling mistakes, and the output is redirected to an error log file named err.log:
spell error.log

How to redirect screen output (stdout) and errors (stderr) to /dev/null

Try the following syntax
command > /dev/null 2>&1
/path/to/script.py > /dev/null 2>&1

Redirect both standard error and standard out messages to a log file

command > log.txt 2>&1
/path/to/my-appname.py > my-appname.log 2>&1

Conclusion

You learned how to save terminal output to a file when using Linux or Unix-like operating system with modern shell such as Bash or KSH including POSIX syntax. See bash docs here for more info or type the following man command:
man bash

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

Источник

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.

Источник

How to append string/data to a file in Linux

This article will show you how to append a string (or any data) to the end of a file under Linux/Unix. Appending is done very simply by using the append redirect operator >>. Simply use the operator in the format data_to_append >> filename and you’re done. Below are several examples:

Examples to Append Data to a File

  1. To append the string “hello” to file greetings.txt
    echo «hello» >> greetings.txt
  2. To append the contents of the file temp.txt to file data.txt
    cat temp.txt >> data.txt
  3. To append the current date/time timestamp to the file dates.txt
    date >> dates.txt

Take it one step further – Find out how to insert a string to the beginning of a file

realy helpful, thanks!

Thank you, it helped me a lot.

how can add the data to the file without open the file in UNIX/Linux ?

Great article!
Thanks

Thanks, ’twas helpful !!

Thanks a lot.. really helped.:)

Thanks for the comments. Are there any other examples that you think should be added to this article? Anything else you all are looking for?

this was really helpful…

I am having two text file (Let’s assume sample1.txt & sample2.txt). sample1.txt contains only one line “xyz” while sample2.txt contains many lines like
“abc
def
ghi
jkl
mno”

Now I need to create a new file which should contain the contents of both the file like below

“xyz abc
xyz def
xyz ghi
xyz jkl
xyz mno”

Is there any way in Unix to achieve the same ?

Any type of help will be much appreciated.

Was very helpful.
Thanks a lot..

I thank you for your brevity.

How to edit the contents in unix through command

Sir, Your giving append example really helpfull for me. Thax alot

Thank you very much! I was looking for how to set a new line in a txt file, and just add one echo per line in the loop resolve it. Thank you!

Thank you so much! I have been looking for this all the morning!

In response to Prashant:
—————————–
user@host0

]$ for x in `cat sample2.txt`
> do
> echo “`cat sample1.txt` $x” >> sample3.txt
> done
user@host0

]$ cat sample3.txt
xyz abc
xyz def
xyz ghi
xyz jkl
xyz mno

Thanx man. Really helpful tip.

Really halpful . thanks lot..

Hello! Quick question that’s totally off topic. Do you know
how to make your site mobile friendly? My blog looks weird when browsing from my iphone4.
I’m trying to find a theme or plugin that might
be able to resolve this issue. If you have any recommendations, please share.
Cheers!

Thanks a ton. It was really helpful.

I got one question: If i have same file test.txt in multiple directories, like dir1, dir2, dir3 how can I add a string using single command.
i have tried below command (i know i’m stupid)
echo “test” >> dir*/test.txt
and got below error:
-bash: /home/blnc/file*/test.txt: ambiguous redirect

Your help is greatly appreciated in advance

Use this to find all the files called test.txt under the current tree and to append a line:

for f in `find . -name test.txt`; do echo “test” >> $f; done;

I am looking to append a string to a particular string as a reference in sample.txt or sample.xml, Can Someone shed some light on it

to
appended sample.xml with “valid” as reference string

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

How do I write all lines from less to a file?

I’ve piped a command to less , and now I want to save the command’s output to a file. How do I do that?

In this case, I don’t want to use tee , I want a solution directly from less, so that I don’t have to rerun a long-running command if I forgot to use tee .

This question is similar to this one, the only difference is that I want to save all of the lines, not a subset: Write lines to a file from less

3 Answers 3

From less , type s then type the file name you want to save to, then Enter .
From the man page, under COMMANDS :

man page also states that, depending on your particular installation, the s command might not be available. In that case, you could go to line 1 with:

and pipe the whole content to cat with:

i.e. type g or (g or less-than) | $ (pipe then dollar) then cat > filename and Enter .
This should work whether input is a pipe or an ordinary file.

One way to do it without tee is as follows.
less /path/to/input > /path/to/output
The above will overwrite /path/to/output if it already exists.

To do the same, but append to /path/to/output is as follows.
less /path/to/input >> /path/to/output

To save the text in less after you have opened it, you can use the Save File feature.
When in less , press s . Then, type the file name.
If you used a pipe, the file will automatically be written to Working Directory.
If you did not use a pipe, you will open a file with the text (for which you can save).
I believe the file will be opened in vim .

Источник

Shell — Write variable contents to a file

I would like to copy the contents of a variable (here called var ) into a file.

The name of the file is stored in another variable destfile .

I’m having problems doing this. Here’s what I’ve tried:

I’ve also tried the same thing with the dd command. Obviously the shell thought that $var was referring to a directory and so told me that the directory could not be found.

How do I get around this?

6 Answers 6

Use the echo command:

The if tests that $destdir represents a file.

The > appends the text after truncating the file. If you only want to append the text in $var to the file existing contents, then use >> instead:

The cp command is used for copying files (to files), not for writing text to a file.

echo has the problem that if var contains something like -e , it will be interpreted as a flag. Another option is printf , but printf «$var» > «$destdir» will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won’t match. However, because printf only interprets backslashes as escapes in the format string, you can use the %s format specifier to store the exact variable contents to the destination file:

printf «%s» «$var» > «$destdir»

None of the answers above work if your variable:

  • starts with -e
  • starts with -n
  • starts with -E
  • contains a \ followed by an n
  • should not have an extra newline appended after it

and so they cannot be relied upon for arbitrary string contents.

In bash, you can use «here strings» as:

As noted in the comment below, @Trebawa’s answer (formulated in the same room as mine!) using printf is a better approach.

If I understood you right, you want to copy $var in a file (if it’s a string).

All of the above work, but also have to work around a problem (escapes and special characters) that doesn’t need to occur in the first place: Special characters when the variable is expanded by the shell. Just don’t do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Источник

Читайте также:  Windows по английски что это
Оцените статью