Chris Hoffman is Editor-in-Chief of How-To Geek. He’s written about technology for over a decade and was a PCWorld columnist for two years. Chris has written for The New York Times and Reader’s Digest, been interviewed as a technology expert on TV stations like Miami’s NBC 6, and had his work covered by news outlets like the BBC. Since 2011, Chris has written over 2,000 articles that have been read nearly one billion times—and that’s just here at How-To Geek. Read more.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

When you run a command at the bash prompt, it normally prints the output of that command directly to the terminal so you can read it immediately. But bash also allows you to “redirect” the output of any command, saving it to a text file so you can review the output later.

This works in bash on any operating system, from Linux and macOS to Windows 10’s Ubuntu-based bash environment.

Option One: Redirect Output to a File Only

To use bash redirection, you run a command, specify the > or >> operator, and then provide the path of a file you want the output redirected to.

  • > redirects the output of a command to a file, replacing the existing contents of the file.
  • >> redirects the output of a command to a file, appending the output to the existing contents of the file.

Technically, this redirects “stdout”—the standard output, which is the screen—to a file.

Here’s a simple example. The ls command lists files and folders in the current directory. So. when you run the following command, ls will list files and folders in the current directory. But it won’t print them to the screen—it will save them to the file you specify.

You don’t have to specify the path to an existing file. Specify any valid path and bash will create a file at that location.

If you view the contents of the file, you’ll see the ls command’s output. For example, the cat command prints the contents of a file to the terminal:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Remember, the > operator replaces the existing contents of the file with the output of the command. If you want to save the output of multiple commands to a single file, you’d use the >> operator instead. For example, the following command will append system information to the file you specify:

If the file doesn’t already exist, bash will create the file. Otherwise, bash will leave the existing contents of the file alone and append the output to the end of the file.

When you view the contents of the file, you’ll see the results of your second command were appended to the end of the file:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

You can repeat this process as many times as you like to keep appending output to the end of the file.

Option Two: Print Output Normally and Redirect It to a File

You might not like redirecting output with the > or >> operators, as you won’t see the output of the command in the terminal. That’s what the tee command is for. The tee command prints the input it receives to the screen and saves it to a file at the same time.

To pipe the output of a command to tee , printing it to your screen and saving it to a file, use the following syntax:

This will replace anything in the file with the output of the command, just like the > operator.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

To pipe the output of a command to tee , printing to to your screen and saving it to a file, but appending it to the end of the file:

This will append the output to the end of the file, just like the >> operator.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

The bash shell includes some additional, advanced operators that perform similar functions. They’ll be particularly useful if you’re writing bash scripts. Consult the I/O Redirection chapter in the Advanced Bash-Scripting Guide for more detailed information.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

If you’re following OS Radar for quite a while, then you may already have noticed that lots of the posts tell about exporting the result to a text file. This is an awesome feature of Linux where you can export the output of a command to a file at your desired location.

It’s extremely useful in tons of cases. For example, you may end up with a very large output that’s giving you a hard time tracking on the terminal window. Or, you think that you need the information later on. Then, using this feature, you can save the output for later usage.

Today, we’ll dive deeper into the tricks.

This is the most basic format of exporting output to a help file.

For example, let’s export the output of “help” command.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Here, the “>” tells the terminal to export the output to somewhere else. This is the default behavior of the Bash shell. The output of “help” command is redirected to the “help.txt” file.

The file didn’t exist, so it will be created.

Selective export

It’s also possible to selectively export certain part of the output.

For example, when we shared the usage of “history” command in terminal, the entire list is pretty long! You can export the output with the above example with no problem.

Say, you only want to find out the commands you ran with “apt”. For that purpose, we shall be using “grep” – a handy search tool for the Linux environment.

For performing the task, the structure of the command will be something like this –

Now, let’s return to the scenario. Check out all the commands performed with “apt” –

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Export the result to a text file –

Multiple exports to a single file

Need to export all your command outputs into a single file? No need to worry.

How do I save the output of a command to a file?

Is there a way without using any software? I would like to know how.

10 Answers 10

Yes it is possible, just redirect the output (AKA stdout ) to a file:

Or if you want to append data:

If you want stderr as well use this:

or this to append:

if you want to have both stderr and output displayed on the console and in a file use this:

(If you want the output only, drop the 2 above)

To write the output of a command to a file, there are basically 10 commonly used ways.

Overview:

Please note that the n.e. in the syntax column means “not existing”.
There is a way, but it’s too complicated to fit into the column. You can find a helpful link in the List section about it.

The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.

The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

command 2> output.txt

The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.

command 2>> output.txt

The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, it gets overwritten.

Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, the new data will get appended to the end of the file..

command | tee output.txt

The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, it gets overwritten.

command | tee -a output.txt

The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

Bash has no shorthand syntax that allows piping only StdErr to a second command, which would be needed here in combination with tee again to complete the table. If you really need something like that, please look at “How to pipe stderr, and not stdout?” on Stack Overflow for some ways how this can be done e.g. by swapping streams or using process substitution.

command |& tee output.txt

Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, it gets overwritten.

command |& tee -a output.txt

Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

Chris Hoffman is Editor-in-Chief of How-To Geek. He’s written about technology for over a decade and was a PCWorld columnist for two years. Chris has written for The New York Times and Reader’s Digest, been interviewed as a technology expert on TV stations like Miami’s NBC 6, and had his work covered by news outlets like the BBC. Since 2011, Chris has written over 2,000 articles that have been read nearly one billion times—and that’s just here at How-To Geek. Read more.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

When you run a command at the bash prompt, it normally prints the output of that command directly to the terminal so you can read it immediately. But bash also allows you to “redirect” the output of any command, saving it to a text file so you can review the output later.

This works in bash on any operating system, from Linux and macOS to Windows 10’s Ubuntu-based bash environment.

Option One: Redirect Output to a File Only

To use bash redirection, you run a command, specify the > or >> operator, and then provide the path of a file you want the output redirected to.

  • > redirects the output of a command to a file, replacing the existing contents of the file.
  • >> redirects the output of a command to a file, appending the output to the existing contents of the file.

Technically, this redirects “stdout”—the standard output, which is the screen—to a file.

Here’s a simple example. The ls command lists files and folders in the current directory. So. when you run the following command, ls will list files and folders in the current directory. But it won’t print them to the screen—it will save them to the file you specify.

You don’t have to specify the path to an existing file. Specify any valid path and bash will create a file at that location.

If you view the contents of the file, you’ll see the ls command’s output. For example, the cat command prints the contents of a file to the terminal:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Remember, the > operator replaces the existing contents of the file with the output of the command. If you want to save the output of multiple commands to a single file, you’d use the >> operator instead. For example, the following command will append system information to the file you specify:

If the file doesn’t already exist, bash will create the file. Otherwise, bash will leave the existing contents of the file alone and append the output to the end of the file.

When you view the contents of the file, you’ll see the results of your second command were appended to the end of the file:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

You can repeat this process as many times as you like to keep appending output to the end of the file.

Option Two: Print Output Normally and Redirect It to a File

You might not like redirecting output with the > or >> operators, as you won’t see the output of the command in the terminal. That’s what the tee command is for. The tee command prints the input it receives to the screen and saves it to a file at the same time.

To pipe the output of a command to tee , printing it to your screen and saving it to a file, use the following syntax:

This will replace anything in the file with the output of the command, just like the > operator.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

To pipe the output of a command to tee , printing to to your screen and saving it to a file, but appending it to the end of the file:

This will append the output to the end of the file, just like the >> operator.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

The bash shell includes some additional, advanced operators that perform similar functions. They’ll be particularly useful if you’re writing bash scripts. Consult the I/O Redirection chapter in the Advanced Bash-Scripting Guide for more detailed information.

Account Information

Share with Your Friends

How to send Linux command output to a file

How to send Linux command output to a file

If you have a command that outputs a lot of data to the terminal, you might want to send that output to a file for easier (or later) viewing or sharing. Jack Wallen shows you how.

If you’re new to the world of the Linux command line, then you know how eye-openingly powerful it can be. In fact, the sky’s the limit with what you can do from the Command Line interface. But, sometimes you’ll run a command and the output flies by so fast you couldn’t possibly catch everything necessary to get the task done.

Open source: Must-read coverage

  • The future of Linux: Fedora project leader Matthew Miller weighs in
  • Why your open-source project definitely should not be the next Kubernetes
  • Master Linux and Docker before the next Linux adoption boom
  • Checklist: Essential support sites for Linux admins

This is especially so when the command is of the informative nature. When you’re working remotely, or on hardware that doesn’t allow you the option to scroll back through the output, what do you do?

You can always pipe the command through the likes of less, so you can page through the output. What if the output of the command is too long, or you need to save it for later or share it with someone to get a second set of eyes on an issue?

For that, you can send the output of the command to a file. It’s really easy and incredibly handy. Let me show you how.

We’ll demonstrate with the simple ip a command, which lists out all the information for your internet connections. If you issue the command ip a, you’ll see all of the details for all of your interfaces. It’s fine if you only have a couple of interfaces.

If you’re also dealing with virtual interfaces or containers, that list can get considerably larger. That’s when you’ll want to send the output to a file.

To do that, you’d issue a command like:

Where output_filename is the name of the file you want to create.

You can then view the contents of the file or attach them to an email. If you run that command again, it’ll overwrite the contents of the file with the new output. If you’d like to append the output to the end of the file (so you can keep multiple instances of command output in one location), the command could be:

When appending, you can help yourself out by adding the date to the beginning of the new section like:

This would insert a timestamp ahead of the next ip a output.

And that’s all there is to sending the output of a command to a file in Linux.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Open Source Weekly Newsletter

You don’t want to miss our tips, tutorials, and commentary on the Linux OS and open source applications.

Is there some way of saving all the terminal output to a file with a command?

  • I’m not talking about redirection command > file.txt
  • Not the history history > file.txt , I need the full terminal text
  • Not with hotkeys !

Something like terminal_text > file.txt

4 Answers 4

You can use script . It will basically save everything printed on the terminal in that script session.

You can start a script session by just typing script in the terminal, all the subsequent commands and their outputs will all be saved in a file named typescript in the current directory. You can save the result to a different file too by just starting script like:

To logout of the script session (stop saving the contents), just type exit .

Here is an example:

Now if I read the file:

script also has many options e.g. running quietly -q ( –quiet ) without showing/saving program messages, it can also run a specific command -c ( –command ) rather than a session, it also has many other options. Check man script to get more ideas.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

I too faced the same problem and after some search came up with this solution:

Add to your .bash_aliases this:

And to the end of your .bashrc file add this:

After you’ve done this, “script” command will be executed once in every terminal session, logging everything to

If you want, you can save current session log after the fact (in the end of the session) by typing savelog or savelog logname – this will copy current raw log to

/Terminal_typescripts/manual and also create readable .txt log in this folder. (If you forget to do so, raw log files will still be in their folder; you’ll just have to find them.) Also you may start recording to a new log file by typing startnewlog .

There will be a lot of junk log files, but you can clean old ones from time to time, so it’s not a big problem.

I’m building an opensource project from source (CPP) in Linux. This is the order:

While compiling I’m getting lot of compiler warnings. I want to start fixing them. My question is how to capture all the compiler output in a file?

$make > file is not doing the job. It’s just saving the compiler command like g++ -someoptions /asdf/xyz.cpp I want the output of these command executions.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

10 Answers 10

The compiler warnings happen on stderr , not stdout , which is why you don’t see them when you just redirect make somewhere else. Instead, try this if you’re using Bash:

The & means “redirect stdout and stderr to this location”. Other shells often have similar constructs.

In a bourne shell:

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

Lots of good answers so far. Here’s a frill:

will let you watch the output scroll past.

The output went to stderr. Use 2> to capture that.

Assume you want to hilight warning and error from build ouput:

Try make 2> file . Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn’t work, check your shell manual for how to divert standard error.

The > character does not redirect the standard error. It’s useful when you want to save legitimate output without mucking up a file with error messages. But what if the error messages are what you want to save? This is quite common during troubleshooting. The solution is to use a greater-than sign followed by an ampersand. (This construct works in almost every modern UNIX shell.) It redirects both the standard output and the standard error. For instance:

Have a look there, if this helps: another forum

In this tutorial, we will show you how to import the files using the curl instruction while working on the various Linux distributions as well as Unix-like and macOS-type operating systems.

Make sure you have any Linux distribution or any Unix-like operating system installed on your system. Users must have some sudo rights to use the system.

Open the command-line shell using the Application area of the Linux desktop. You can find the version of curl utility installed on your system using the below “version” command:

Example 01: Save Pdf File via Curl

We will be having a very simple example of saving pdf files in the Linux system using a curl command. Suppose you find some pdf book file regarding Linux introduction for beginners on the web and you want to download it on your Linux system. For this purpose, we will be using a very simple “curl” command in our command terminal of Linux as presented in the image. The command keyword “curl” has been followed by a link or URL of the particular pdf file, as shown:

It is possible to save the specific pdf book file to a specific name output file created by you, using the below-stated command. We have been using “new.pdf” as the name of the output file followed by the link to the pdf file. You can see the download statistics of this particular pdf file.

Now open the home directory and you will find your newly downloaded pdf file in it, e.g., new.pdf. Right-click on the file and tap on the “Open with Pdf” option to open this pdf file and check whether it works properly or not.

You can see the file has been successfully saved in your Linux system and working right.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Example 02: Save Html File via Curl

Imagine you want to search for simple and beginner-level Linux files, e.g, pdf or HTML, to save these files in your Linux system using Curl instruction. You have opened one web page and copied its URL on the Linux terminal within the “curl” command. Note that we have been using the “-o” flag in our command to forcefully save this “html” type page into a new output file “output.htm”. Now, this new file “output.html” can be found in the home directory.

Open the home directory of your Linux distribution to see a file “output.html” is in it. When you double-click on this file, it will open the webpage provided in the above query as a URL.

You can see, the “.html” file will be automatically opened in your browser of Linux system, probably Mozilla Firefox.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

The above illustration was about saving a URL or pdf file into a system output file with some name decided by a user. Now, we will see how to save the URL data into a file without naming a file using the simple curl command.

So, execute the below query in the shell for this. You can see we have been using the capital “-O” flag followed by a URL in this query to save the data without specifying the file name. You can see it will show you some statistics about the web.

Now, when you again check the home directory of your Linux system, you will find a file with a name as it is mentioned in the URL of the “html” webpage used in the command. Open this file by double-tapping it.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Your browser, e.g., Mozilla Firefox, will open a link to the Html page, as shown in the screenshot image below.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Example 03: Save Html File via Curl

As you have an idea that the “curl” utility is standard for saving the curl output to a file. To understand the concept of saving curl output into files using the “curl” command, we will be having another example. In this example, we will be using a new weblink to save its web page into a file of our Linux system. This file has some information regarding the software of GNU. So we are using the curl command along with the lower case “-o” flag to save the HTML page output into a user modified name file. We are using the “mygettext.html” name for the output saving file.

The execution of the below command is showing some information regarding the HTML page.

Now it’s time to open your Linux Home directory by clicking on the folders icon. You can see the file has been generated with your specified name in the command as “mygettext.html”.

Right-click and tap on “Open mygettext.html” to open this file to check if it works or not.

Our browser has been opened and it shows the Html page as output, which was mentioned in the “curl” command.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Now, we will use the capital “-O” flag in the curl command to save the Html page into a file without creating a new file name. Hence, try to execute the below query in the terminal of Ubuntu 20.04.

Take a look at the home directory. It has created a file with a standard name used for the page. Double-click on it to see the page.

The browser Mozilla Firefox has opened the Html page as specified in the URL of the curl command.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Conclusion:

We have brilliantly done with many of the examples for saving the curl output, e.g., Html or pdf file, into the file using the CURL command in the command shell of Linux based system.

About the author

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Have you ever been in a situation where you wanted to send the output of a Linux command to your colleague or friend to get help? This simple Linux hack will definitely be useful to you. You can save a Linux command output to an image or a file. All you need to have is only ImageMagick. This can be helpful when you need to send the output to a technical support person or a colleague.

Save Linux Command Output To An Image

Install ImageMagick tool first. It is available in the default repositories of most Linux distributions.

For example, to install ImageMagick in Arch Linux and its derivatives, run:

On Debian, Ubuntu and other DEB-based systems, you can install it a shown below.

Now, to save a output of any Linux command to an image file, just run the following command:

The above command will save the ifconfig command output to an Image and save it in the current working directory. Let us bread down the above command and see what each option does.

  • ip a will display the IP address of your Linux system.
  • convert command will save the output to an Image.
  • label:@- myipaddress.png will save the command output to the image named myipaddress.png.

Here is the output of the above command in my Ubuntu 18.04 desktop system.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Here is another one. I saved my Linux Kernel output to an Image.

Sample output:

What we have seen above is we have saved the command’s output in an Image file.We also can save the output on an existing Image file. To do this, run:

This command will print the output of “lsb_release -a” command to an image called image.png and saves it with a new name “systemdetails.png”.

Here is the output of the above command:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Pretty easy, isn’t? You can save the output of any command in an image file and send it to anyone who can help you to fix your system.

Troubleshooting

In recent Ubuntu Linux distributions, certain convert operations are restricted for security reasons. If you tried the above commands in Ubuntu OS, you might be encountered with the following error message:

In that case, you need to edit policy.xml configuration file and change the policy.

Find the following line:

Comment out or remove the following line:

Save and close the file. Now you can be able to save the command’s in the image file.

Save Linux Command Output To A Text File

We know how to save a command’s output to/into a image. We can also save the output of a Linux command to a file too.

For example, to save the “ip addr” command’s output to a file called myipaddress.txt, run:

To verify it, view the text file using your favorite text viewers. Or, we can do using “cat” command like below.

The following command will save my pacman.log to a file called mylogs.txt.

And, we can easily save the IP details using command:

You might wanted to write the output of a command to multiple files. Here is how to do it.

The above command will write the output of “uname -a” command to file1 and file2. If the files doesn’t exist already, it will create them.

By default, it will overwrite the contents of file1 and file2. If you want to append the output to the existing contents, use -a flag like below.

This command will not overwrite the existing contents of file1 and file2. Instead, it will simply append the output of the ifconfig command to file1 and file2. In other words, these two files now have the outputs of “uname -a” and “ip a” commands.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

To write the output of a command to a file, there are basically 10 commonly used ways.
Please note that the n.e. in the syntax column means “not existing”.
There is a way actually, but it’s too complicated to fit into the column. You can find a helpful link in the List section about it.
Overview:
|| visible in terminal || visible in file || existing
Syntax || StdOut | StdErr || StdOut | StdErr || file
==========++==========+==========++==========+==========++===========
> || no | yes || yes | no || overwrite
>> || no | yes || yes | no || append
|| | || | ||
2> || yes | no || no | yes || overwrite
2>> || yes | no || no | yes || append
|| | || | ||
&> || no | no || yes | yes || overwrite
&>> || no | no || yes | yes || append
|| | || | ||
| tee || yes | yes || yes | no || overwrite
| tee -a || yes | yes || yes | no || append
|| | || | ||
n.e. (*) || yes | yes || no | yes || overwrite
n.e. (*) || yes | yes || no | yes || append
|| | || | ||
|& tee || yes | yes || yes | yes || overwrite
|& tee -a || yes | yes || yes | yes || append
List:
command > output.txt
The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.
command >> output.txt
The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
command 2> output.txt
The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.
command 2>> output.txt
The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
command &> output.txt
Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, it gets overwritten.
command &>> output.txt
Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, the new data will get appended to the end of the file..
command | tee output.txt
The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, it gets overwritten.
command | tee -a output.txt
The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
(*)
Bash has no shorthand syntax that allows piping only StdErr to a second command, which would be needed here in combination with tee again to complete the table. If you really need something like that, please look at “How to pipe stderr, and not stdout?” on Stack Overflow for some ways how this can be done e.g. by swapping streams or using process substitution.
command |& tee output.txt
Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, it gets overwritten.
command |& tee -a output.txt
Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

© 2022 GitHub, Inc.

  • Terms
  • Privacy
  • Security
  • Status
  • Docs
  • Contact GitHub
  • Pricing
  • API
  • Training
  • Blog
  • About

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

When you run a command, it produces some kind of output: either the result of a program is suppose to produce or status/error messages of the program execution details. Sometimes, you may want to store the output of a command in a variable to be used in a later operation.

In this post, we will review the different ways of assigning the output of a shell command to a variable, specifically useful for shell scripting purpose.

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below:

Below are a few examples of using command substitution.

In this first example, we will store the value of who (which shows who is logged on the system) command in the variable CURRENT_USERS user:

Then we can use the variable in a sentence displayed using the echo command like so:

In the command above: the flag -e means interpret any escape sequences ( such as \n for newline) used. To avoid wasting time as well as memory, simply perform the command substitution within the echo command as follows:

Shows Current Logged Users in Linux

Next, to demonstrate the concept using the second form; we can store the total number of files in the current working directory in a variable called FILES and echo it later as follows:

Show Number of Files in Directory

That’s it for now, in this article, we explained the methods of assigning the output of a shell command to a variable. You can add your thoughts to this post via the feedback section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

เมื่อคุณรันคำสั่งที่พร้อมต์ bash โดยปกติแล้วจะพิมพ์เอาต์พุตของคำสั่งนั้นไปยังเทอร์มินัลโดยตรงเพื่อให้คุณสามารถอ่านได้ทันที แต่ทุบตียังช่วยให้คุณสามารถ“ เปลี่ยนเส้นทาง” เอาท์พุทของคำสั่งใด ๆ บันทึกไว้ในไฟล์ข้อความเพื่อให้คุณสามารถตรวจสอบผลลัพธ์ในภายหลัง.

สิ่งนี้สามารถใช้งานได้กับระบบปฏิบัติการทุบตีจาก Linux และ macOS ไปจนถึงระบบปฏิบัติการทุบตีที่ใช้ Ubuntu บน Windows 10.

ตัวเลือกที่หนึ่ง: เปลี่ยนเส้นทางการส่งออกเป็นไฟล์เท่านั้น

ในการใช้การเปลี่ยนเส้นทาง bash คุณเรียกใช้คำสั่งระบุ > หรือ >> โอเปอเรเตอร์แล้วระบุเส้นทางของไฟล์ที่คุณต้องการให้เปลี่ยนเส้นทางไปที่เอาต์พุต.

  • > เปลี่ยนทิศทางเอาต์พุตของคำสั่งไปยังไฟล์แทนที่เนื้อหาที่มีอยู่ของไฟล์.
  • >> เปลี่ยนทิศทางเอาต์พุตของคำสั่งไปยังไฟล์ต่อท้ายเอาต์พุตไปยังเนื้อหาที่มีอยู่ของไฟล์.

ในทางเทคนิคสิ่งนี้จะเปลี่ยนเส้นทาง“ stdout” – เอาต์พุตมาตรฐานซึ่งเป็นหน้าจอไปยังไฟล์.

นี่คือตัวอย่างง่ายๆ LS คำสั่งรายการไฟล์และโฟลเดอร์ในไดเรกทอรีปัจจุบัน ดังนั้น. เมื่อคุณเรียกใช้คำสั่งต่อไปนี้, LS จะแสดงรายการไฟล์และโฟลเดอร์ในไดเรกทอรีปัจจุบัน แต่จะไม่พิมพ์ลงบนหน้าจอ แต่จะบันทึกลงในไฟล์ที่คุณระบุ.

คุณไม่จำเป็นต้องระบุพา ธ ไปยังไฟล์ที่มีอยู่ ระบุพา ธ ที่ถูกต้องและ bash จะสร้างไฟล์ที่ตำแหน่งนั้น.

หากคุณดูเนื้อหาของไฟล์คุณจะเห็น LS เอาต์พุตของคำสั่ง ตัวอย่างเช่น แมว คำสั่งพิมพ์เนื้อหาของไฟล์ไปยังเทอร์มินัล:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

จำไว้ว่า > โอเปอเรเตอร์จะแทนที่เนื้อหาที่มีอยู่ของไฟล์ด้วยเอาต์พุตของคำสั่ง หากคุณต้องการบันทึกผลลัพธ์ของคำสั่งหลายคำในไฟล์เดียวคุณจะต้องใช้ >> ผู้ประกอบการแทน ตัวอย่างเช่นคำสั่งต่อไปนี้จะผนวกข้อมูลระบบเข้ากับไฟล์ที่คุณระบุ:

หากไฟล์นั้นไม่มีอยู่ bash จะสร้างไฟล์ มิเช่นนั้น bash จะปล่อยเนื้อหาที่มีอยู่ของไฟล์ไว้ตามลำพังและผนวกเอาท์พุทต่อท้ายไฟล์.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

คุณสามารถทำขั้นตอนนี้ซ้ำหลาย ๆ ครั้งตามที่คุณต้องการเก็บเอาท์พุทต่อท้ายไฟล์.

ตัวเลือกที่สอง: พิมพ์งานปกติและเปลี่ยนเส้นทางไปยังไฟล์

คุณอาจไม่ชอบเปลี่ยนเส้นทางผลลัพธ์ด้วย > หรือ >> ตัวดำเนินการเนื่องจากคุณจะไม่เห็นผลลัพธ์ของคำสั่งในเทอร์มินัล นั่นคือสิ่งที่ ที คำสั่งสำหรับ คำสั่ง tee พิมพ์อินพุตที่ได้รับไปที่หน้าจอ และ บันทึกลงในไฟล์ในเวลาเดียวกัน.

เพื่อไพพ์เอาต์พุตของคำสั่งให้ ที , พิมพ์ไปที่หน้าจอของคุณและบันทึกลงในไฟล์ใช้ไวยากรณ์ต่อไปนี้:

สิ่งนี้จะแทนที่สิ่งใด ๆ ในไฟล์ด้วยผลลัพธ์ของคำสั่งเช่นเดียวกับ > ผู้ประกอบการ.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

เพื่อไพพ์เอาต์พุตของคำสั่งให้ ที , พิมพ์ไปที่หน้าจอของคุณและบันทึกลงในไฟล์ แต่ต่อท้ายไฟล์:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

bash shell รวมถึงตัวดำเนินการขั้นสูงเพิ่มเติมบางอย่างที่ทำหน้าที่คล้ายกัน มันจะมีประโยชน์อย่างยิ่งหากคุณกำลังเขียนสคริปต์ทุบตี ศึกษาบท I / O Redirection ในคู่มือการใช้งาน Bash-Scripting ขั้นสูงสำหรับรายละเอียดเพิ่มเติม.

Home » SysAdmin » How to Use the Linux watch Command with Examples

To repeatedly run a command or job in regular time intervals while working in Linux, you can use cron jobs or bash scripts. However, Linux also offers a more straightforward, built-in solution – the watch command.

In this tutorial, you will learn the watch command syntax, how it works, and the different things it can help you do.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

  • A system running a Linux distribution (learn how to install Ubuntu 20.04, how to install CentOS 7, or how to install Arch Linux)
  • An account with sudo privileges
  • Access to the terminal window/command line

Linux watch Command Overview

The watch command is a built-in Linux utility used for running user-defined commands at regular intervals. It temporarily clears all the terminal content and displays the output of the attached command, along with the current system date and time.

By default, the watch command updates the output every two seconds. Press Ctrl+C to exit out of the command output.

The watch command is useful when you need to monitor changes in a command output over time. This includes disk usage, system uptime, or tracking errors.

Linux Watch Command Syntax

The watch command uses the following syntax:

  • [option] : Adding an option changes the way the watch command behaves. Available options are listed below.
  • [command] : A user-defined command you want to run repeatedly.

The watch command options include:

-n , –interval Allows you to specify the interval between output updates.
-d , –differences Highlights the differences between output updates.
-g , –chgexit Exits the watch command when the output of the user-defined command changes.
-t , –no-title Removes the header showing the interval, command, and current time and date.
-b , –beep Plays a sound alert (beep) if the command exits with an error.
-p , –precise Attempts to run the command after the exact number of seconds defined by the –interval option.
-e , –errexit Stops output updates on error and exits the command after a key press.
-c , –color Interprets ANSI color and style sequences.
-x , –exec Passes the user-defined command to exec , reducing the need for extra quoting.
-w , –no-linewrap Turns off line wrapping and truncates long lines instead.
-h , –help Displays help text and exits.
-v , –version Displays version information and exits.

Linux Watch Command Examples

Here are some of the ways you can use the watch command options to achieve different results:

Run Command with a Custom Interval

Set a custom interval to run a user-defined command and show the output by using the -n or –interval option:

For instance, to display the system time and date every 5 seconds, run:

Note: The -n option allows you to use fractions of a second, with a minimum interval of 0.1 seconds. When entering decimals, both a period (.) and a comma (,) work for any locale.

Highlighting Changes Between Updates

Use the -d or –difference option to highlight changes between successive output updates:

For example, display the system date and time in the default 2-second interval with the changes highlighted:

Pass =cumulative to the -d option if you want all the values that have ever changed to stay highlighted:

Exit on Change

The -g or –chgexit option causes the watch command to exit if there is a change in the output:

As an example, adding the free command monitors your system’s memory consumption and exits if the value changes:

Hide the watch Command Header

Turn off the header containing the interval time, user-defined command, and current system time in the watch command output by using the -t or –no-title option:

Returning to the example of displaying the system date and time, this time without the header:

Alert on Error

The watch command uses the beep package to play a sound alert if the output update fails due to an error. To do this, use the -b or –beep option:

Note: if you don’t have the beep package installed, add it with sudo apt install beep command.

Using Complex Commands

The watch command also allows you to use more complex user-defined commands, with their own arguments and options. One way to do this is to use the backslash (‘\’) symbol:

Using the command above brings you to the next line in the terminal, where you need to add the user-defined command. Once you hit Enter, it executes the command. For instance:

Another option is to add the user-define command in single quotation marks:

Using the example above, the command would be:

After reading this tutorial, you should have a better understanding of how the watch command works and what you can use it for.

For a more comprehensive overview of Linux commands, check out our Linux command cheat sheet.

In this article, we will learn to create a file in the Linux/Unix system using the terminal. In the Linux/Unix system, there are the following ways available to creating files.

  1. Using the touch command
  2. Using the cat command
  3. Using redirection operator
  4. Using the echo command
  5. Using the heredoc
  6. Using the dd command

1. Create a file in the Linux/Unix system using the touch command.

The touch command is used to create file/files without any content and update the access date or modification date of a file or directory in the Linux system. This is the simplest way to create a file in Linux/Unix using the terminal.

Syntax:

The general syntax of the touch command is as follows:

Create a file using the touch command in Linux/Unix system.

In this example, using the touch command we can create a file in the Linux system. Before executing the touch command, we will check that how many files available in our current directory using the below command.

After using the below command a new file created newfile.txt in the current directory.

Example :

How to save the output of a command to a file in bash (aka the linux and macos terminal)

To ensure that the file is created or not we will again execute the ls command to list the directory contents.

2. Create a File in the Linux/Unix system using the cat command.

The cat (concatenate) command is used to create, view, concatenate files in the Linux operating system. The touch command is also used to create a file in a Linux system without content whereas the cat creates files with some content. The cat command reads the content of a file and prompts it.

Syntax

The general syntax of the cat command is as follows:

Create a file with some content using the cat command in Linux/Unix system.

To create a file with some content, we use the cat command and file name after that write some content and press CTRL + C when writing is complete as shown below.

Example :

Display contents of the files using the cat command in the Linux system.

The cat command is also used to view the contents of the file. After using the cat command along with the file name contents of the file will be prompt as shown below.

3. Create a file in the Linux/Unix system using a redirection operator.

In the Linux/Unix system a redirection operator is also used to create a file.

Example :

How to save the output of a command to a file in bash (aka the linux and macos terminal)

4. Create a file in the Linux/Unix system using the echo command.

The echo command is also used to create a new file in the Linux system.

Create a new file without contents in the Linux system using the echo command.

To create a file without contents, we use the echo command with a redirection operator followed by the file name as shown below.

Example :

How to save the output of a command to a file in bash (aka the linux and macos terminal)

Create a new file with some contents in the Linux system using the echo command.

To create a file with some contents, we use the echo command followed by the text, a redirection operator, and the file name as shown below.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

5. Create a file in the Linux/Unix system using heredoc.

heredoc stands for here document. The heredoc delimiter is a type of redirection. It allows passing multiple lines of input to a command.

The general syntax of heredoc. Important

Create a file with multiple lines of contents using a heredoc delimiter in the Linux system.

To create a file using heredoc, we use the cat command with heredoc delimiter in the Linux system as shown below.

Example :

How to save the output of a command to a file in bash (aka the linux and macos terminal)

6. Create a file in the Linux/Unix system using the dd command.

The dd command is mainly used to converts and copy files. To check more details about the dd command. We can also create a large file using the dd command.

Create a large file in the Linux system using the dd command.

To create a large file, we use the dd command as shown below.

How do I save the output of a command to a file?

Is there a way without using any software? I would like to know how.

10 Answers 10

Yes it is possible, just redirect the output (AKA stdout ) to a file:

Or if you want to append data:

If you want stderr as well use this:

or this to append:

if you want to have both stderr and output displayed on the console and in a file use this:

(If you want the output only, drop the 2 above)

To write the output of a command to a file, there are basically 10 commonly used ways.

Overview:

Please note that the n.e. in the syntax column means “not existing”.
There is a way, but it’s too complicated to fit into the column. You can find a helpful link in the List section about it.

The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.

The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

command 2> output.txt

The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.

command 2>> output.txt

The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, it gets overwritten.

Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, the new data will get appended to the end of the file..

command | tee output.txt

The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, it gets overwritten.

command | tee -a output.txt

The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

Bash has no shorthand syntax that allows piping only StdErr to a second command, which would be needed here in combination with tee again to complete the table. If you really need something like that, please look at “How to pipe stderr, and not stdout?” on Stack Overflow for some ways how this can be done e.g. by swapping streams or using process substitution.

command |& tee output.txt

Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, it gets overwritten.

command |& tee -a output.txt

Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, the new data will get appended to the end of the file.

file command is used to determine the type of a file. .file type may be of human-readable(e.g. ‘ASCII text’) or MIME type(e.g. ‘text/plain; charset=us-ascii’). This command tests each argument in an attempt to categorize it.

It has three sets of tests as follows:

  • filesystem test: This test is based on the result which returns from a stat system call. The program verifies that if the file is empty, or if it’s some sort of special file. This test causes the file type to be printed.
  • magic test: These tests are used to check for files with data in particular fixed formats.
  • language test: This test search for particular strings which can appear anywhere in the first few blocks of a file.

Syntax:

Example: Command displays the file type

Options:

    -b, –brief : This is used to display just file type in brief mode.

Syntax:

Example:

Here, we can see that file type without filename.
* option : Command displays the all files’s file type.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

The output shows all files in the home directory
directoryname/* option : This is used to display all files filetypes in particular directory.

Syntax:

Example:

The output shows all files in a particular directory.
[range]* option: To display the file type of files in specific range.

Syntax:

Example:

How to save the output of a command to a file in bash (aka the linux and macos terminal)

The output shows the range of files.
-c option: Cause a checking printout of the parsed form of the magic file. This option is usually used in conjunction with the -m flag to debug a new magic file before installing it.

Example:

-f option: Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or atleast one filename argument must be present; to test the standard input, use ‘-’ as a filename argument.

Syntax:

-F option : File and file type are separated by :. But we can change separator using -F option

Syntax:

Example:

The output shows file and file types are separated by and +.
-i option: To view mime type of file.

Syntax:

Example:

-N option: Don’t pad filenames so that they align in the output.

Example:

How to save the output of a command to a file in bash (aka the linux and macos terminal)
-s option: For special files

Syntax:

Example:

filenames: Displays file types of multiple files

Syntax:

Example:

-z option: Try to look inside compressed files.

Example:

–help option: Print a help message and exit.

How to save the output of a command to a file in bash (aka the linux and macos terminal)

I have several Terminal commands I use for troubleshooting purposes, by typing them in one by one into the terminal window.

These commands require the user’s password to be entered.

I’m looking for a way to create a universal (script) file with these commands. I want to be able to run the file on a Mac just by double-clicking on it or dragging the file over the Terminal icon.

I have never done anything like this before. Is there any way to create such a script? Please advise.

2 Answers 2

Short answer

A .command script should do the trick

Step-by-step

  1. Open TextEdit and create a new file
  2. Convert it to plain text by clicking Format > Make Plain Text

Add your commands, one per line. For example, you could do:
#! /bin/bash cd

/Desktop mkdir myCoolFolder cd myCoolFolder

/Desktop/myCommandScript.command in your terminal, where

/Desktop/myCommandScript.command is the path to your script. This will give the terminal permission to run the file.

  • You’re done! Double-click the file to run. Dragging over the terminal icon will also work.
  • Notes:

    • If you need to do something that requires root (admin) access, you can prefix your command with sudo . When the script runs, you’ll have to enter your password (and be an administrator)
    • If the end user isn’t an administrator, but you need to do something that required root access, you can use su someAdminName , which will perform the command as someAdminName (you’ll need his password).

    You can also see here on Stack Overflow for a bit more information.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    A script is just a series of commands, so you could put it into a bash script.

    Now, this all depends on the they types of command and whether or not they require user intervention.

    However, if you are getting diagnostic info, for example, you can have a script that does

    Home » SysAdmin » Linux alias Command: How to Use It With Examples

    Depending on the type of work you do on your Linux system, you may need to enter the same long and complicated commands frequently. The alias command lets you create shortcuts for these commands, making them easier to remember and use.

    In this tutorial, we will show you how you can create, review, and remove command aliases in Linux.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    • A system running a Linux distribution
    • An account with sudo privileges
    • Access to the terminal window or command line
    • A text editor, such as Vim or nano

    What Is an Alias in Linux?

    In Linux, an alias is a shortcut that references a command. An alias replaces a string that invokes a command in the Linux shell with another user-defined string.

    Aliases are mostly used to replace long commands, improving efficiency and avoiding potential spelling errors. Aliases can also replace commands with additional options, making them easier to use.

    Linux Alias Syntax

    The alias command uses the following syntax:

    The different elements of the alias command syntax are:

    • alias : Invokes the alias command.
    • [option] : Allows the command to list all current aliases.
    • [name] : Defines the new shortcut that references a command. A name is a user-defined string, excluding special characters and ‘alias’ and ‘unalias’, which cannot be used as names.
    • [value] : Specifies the command the alias references. Commands can also include options, arguments, and variables. A value can also be a path to a script you want to execute.

    Note: Enclosing the value in single quotation marks () will not expand any variables used with the command. To expand the variables, use double quotation marks ().

    Create Aliases in Linux

    There are two types of aliases to create in Linux:

    • Temporary. Add them using the alias command.
    • Permanent. These require to edit system files.

    Create a Temporary Alias in Linux

    Use the alias command to create a temporary alias that lasts until the end of the current terminal session. For instance, creating c as an alias for the clear command:

    Note: The alias command allows you to include multiple commands as the value by dividing them with the pipe symbol (|).

    If you want to reference any additional command options when creating an alias, include them as a part of the value. For example, adding move as an alias for the mv command with the option of asking for confirmation before overwriting:

    Note: Learn more about the mv command in our guide to moving directories in Linux.

    Another use for aliases is to create a shortcut for running scripts. To do this, provide the absolute path to the script as the value:

    In this example, using frename as a command runs the file_rename.sh bash script.

    Create a Permanent Alias in Linux

    To make an alias permanent, you need to add it to your shell configuration file. Depending on the type of shell you are using, use:

    /.bashrc
    Zsh shell:

    /.zshrc
    Fish shell:

    Start by opening the shell configuration file in a text editor. In this example, we are using the Bash shell and nano text editor:

    Scroll down until you find a section that lists default system aliases. For ease of use, create a separate section with a descriptive comment and add your aliases using the alias command syntax.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Once you add all of the new alises, press Ctrl+X, type Y and press Enter to save the changes to the configuration file.

    The new aliases automatically load in the next terminal session. If you want to use them in the current session, load the configuration file using the source command:

    List All Aliases in Linux

    Using the alias command on its own displays a list of all currently set aliases:

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Another method is to add the -p flag. This option displays the list in a format suitable for input to the shell:

    Remove Aliases in Linux

    To remove an alias, use the unalias command with the following syntax:

    For instance, to remove the frename alias:

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Adding the -a option allows you to remove all aliases:

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    The example above shows how alias does not return any results after the unalias -a command.

    After reading this tutorial, you should be able to use the alias command to create and manage aliases on your Linux system. This will help streamline your work and make terminal commands easier to use.

    To learn more about other commands in Linux, check out our Linux commands cheat sheet.

    Sometimes you may need to write grep output to file in Linux for later use. There are many ways to do this. In this article, we will look at a couple of ways to easily save grep output to file in Linux.

    How to Save Grep Output to File in Linux

    Here is how to save grep output to file in Linux.

    1. Overwrite grep output to file

    You can easily write grep output to another file using > operator. Here is the syntax

    In the above statement, you need to mention search string, the file where you want grep to search (old_file_path) and the file where you want grep to write the result (new_file_path).

    Here is an example to search “test” in our file /home/data.txt and write to file /etc/result.txt

    In the above statement, if you do not specify full file paths grep will look for these files in your present working directory. Also if the destination file result.txt does not exist, it will be newly created. Also, its content will be completely overwritten with the result of grep command.

    If you only want to append the grep result to this file, follow the steps below.

    2. Append grep output to file

    In this case, we will append the result of grep command to new file, instead of overwriting it, using >> operator, instead of using > operator.

    In the above statement also you need to specify search string, path of the file to be searched (old_file_path) and path of the file (new_file_path) to which you want to append the grep result.

    Here is an example to search “test” in our file /home/data.txt and append to file /etc/result.txt

    In the above statement, if you do not specify full file paths grep will look for these files in your present working directory. In this case, the result of grep command will simply be appended to result.txt.

    If you want to automate this task, you can simply create a cronjob for it. Here is an example. Open crontab file.

    Add the following line to run the above grep command every day at 10 am.

    Save and close the file. Now, every day at 10am grep command will search data.txt for “test” string and append the output to result.txt file.

    In this article, we have looked at how to save output of grep command to file. It is very useful to look for specific strings from files that are updated regularly, such as server logs, and filter the result to another files. You may overwrite or append the result to a file, depending on your requirement.

    echo is a shell built-in command that is used to print the information/message to your terminal. It is the most popular command that is available in most Linux distributions and is typically used in bash scripts and batch files to print status text/string to the screen or a file.

    In this article, I will show you how to use the echo command in Linux shell scripts.

    How to Work With echo Command in Linux

    When learning shell scripting this is the first command you will learn about to print something in your terminal. echo will print the output to stdout or you can also redirect the output to files. There are two versions of echo. One is bash builtin and the second one is an external command.

    NOTE: Always builtin version takes precedence over external command.

    Use the type command to get the path information about the echo command.

    To get the list of options supported for the echo command, use the help option.

    Example 1: No Arguments to echo Command

    When you call the echo command without passing any arguments it prints an empty line.

    an echo with no arguments

    Example 2: Use echo With and Without Quotes

    You can pass arguments to echo command with or without quotes. Take a look at the below example. I am printing the same statement with single and double quotes and without quotes and getting the same result.

    echo print output

    There is a significant difference in when to use single and double quotes. When you use single quotes and any word contains a single quote then it will be treated as the end of quotes. Take a look at the below example where isn’t contains single quotes and is treated as the end of quotes.

    In this case, using double quotes will make more sense.

    Echo Single Vs Double Quotes

    Example 3: Printing Variables with Echo Command

    Values stored in variables can be printed to the terminal using the echo command. When you use single quotes variable $ will be interpreted as text and will not be expanded to its assigned value (welcome).

    How to save the output of a command to a file in bash (aka the linux and macos terminal)Echo Printing Variable Value

    Example 4: Redirecting Output to File

    You can redirect output to a file instead of printing it in a terminal using the redirection operator ( > and >> ).

    • Using > operator will create a new file if not exists and write the data and if the file exists it will overwrite the data.
    • Using >> operator will create a new file if not exists and append the data if the file exists.

    Redirecting Output to File

    Example 5: Supported Arguments

    echo command supports three arguments.

    Echo Arguments

    By default when you run the echo command new line character is automatically appended at the end. If you want to suppress this behavior use -n flag.

    Suppress New Line Character

    By using the -E flag, the echo statement will treat all backslash-escaped characters as plain text. It is not mandatory to use -E flag because echo by default will not treat these as special characters.

    Escaped Characters

    To use backslash-escaped characters you have to use -e flag.

    Example 6: Escaped Characters

    echo command supports escape characters like newline, tab, vertical tab, and a few more. You can get the list of supported characters from the help command.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)Escaped Characters

    Let’s see frequently used escape characters in action. Note you have to use -e argument for any escape characters to be effective.

    Newline character(\n) – This will be one of the commonly used escape characters. When you use \n it will add new lines.

    Horizontal tab(\t) – To create horizontal tabs use \t which adds a single tab in your statement.

    Vertical tab(\v) – To create vertical tabs use \v .

    Carriage Return(\r) – Removes everything that comes before \r and prints only what is after \r .

    Suppress Further Output(\c) – Carriage return removes everything that comes before it and \c will remove everything that comes after it.

    If you want to treat any escape characters as normal characters you can use \\ . Let’s say you want \c to be treated as a normal value then use \\ followed by escape character \c .

    That’s it for this article. The echo is a simple command to use and very easy to learn. We will catch you up with more shell script-related articles soon.

    This article describes how to create, edit, run, and save scripts in the Script Pane.

    How to create and run scripts

    You can open and edit Windows PowerShell files in the Script Pane. Specific file types of interest in Windows PowerShell are script files ( .ps1 ), script data files ( .psd1 ), and script module files ( .psm1 ). These file types are syntax colored in the Script Pane editor. Other common file types you may open in the Script Pane are configuration files ( .ps1xml ), XML files, and text files.

    The Windows PowerShell execution policy determines whether you can run scripts and load Windows PowerShell profiles and configuration files. The default execution policy, Restricted, prevents all scripts from running, and prevents loading profiles. To change the execution policy to allow profiles to load and be used, see Set-ExecutionPolicy and about_Signing.

    To create a new script file

    On the toolbar, click New, or on the File menu, click New. The created file appears in a new file tab under the current PowerShell tab. Remember that the PowerShell tabs are only visible when there are more than one. By default a file of type script ( .ps1 ) is created, but it can be saved with a new name and extension. Multiple script files can be created in the same PowerShell tab.

    To open an existing script

    On the toolbar, click Open, or on the File menu, click Open. In the Open dialog box, select the file you want to open. The opened file appears in a new tab.

    To close a script tab

    Click the Close icon (X) of the file tab you want to close or select the File menu and click Close.

    If the file has been altered since it was last saved, you’re prompted to save or discard it.

    To display the file path

    On the file tab, point to the file name. The fully qualified path to the script file appears in a tooltip.

    To run a script

    On the toolbar, click Run Script, or on the File menu, click Run.

    To run a portion of a script

    1. In the Script Pane, select a portion of a script.
    2. On the File menu, click Run Selection, or on the toolbar, click Run Selection.

    To stop a running script

    There are several ways to stop a running script.

    • Click Stop Operation on the toolbar
    • Press CTRL + BREAK
    • Select the File menu and click Stop Operation.

    Pressing CTRL + C also works unless some text is currently selected, in which case CTRL + C maps to the copy function for the selected text.

    How to write and edit text in the Script Pane

    You can copy, cut, paste, find, and replace text in the Script Pane. You can also undo and redo the last action you just performed. The keyboard shortcuts for these actions are the same shortcuts used for all Windows applications.

    To enter text in the Script Pane

    1. Move the cursor to the Script Pane by clicking anywhere in the Script Pane, or by clicking Go to Script Pane in the View menu.
    2. Create a script. Syntax coloring and tab completion provide a richer editing experience in Windows PowerShell ISE.
    3. See How to Use Tab Completion in the Script Pane and Console Pane for details about using the tab completion feature to help in typing.

    To find text in the Script Pane

    1. To find text anywhere, press CTRL + F or, on the Edit menu, click Find in Script.
    2. To find text after the cursor, press F3 or, on the Edit menu, click Find Next in Script.
    3. To find text before the cursor, press SHIFT + F3 or, on the Edit menu, click Find Previous in Script.

    To find and replace text in the Script Pane

    Press CTRL + H or, on the Edit menu, click Replace in Script. Enter the text you want to find and the replacement text, then press ENTER .

    To go to a particular line of text in the Script Pane

    In the Script Pane, press CTRL + G or, on the Edit menu, click Go to Line.

    Enter a line number.

    To copy text in the Script Pane

    In the Script Pane, select the text that you want to copy.

    Press CTRL + C or, on the toolbar, click the Copy icon, or on the Edit menu, click Copy.

    To cut text in the Script Pane

    1. In the Script Pane, select the text that you want to cut.
    2. Press CTRL + X or, on the toolbar, click the Cut icon, or on the Edit menu, click Cut.

    To paste text into the Script Pane

    Press CTRL + V or, on the toolbar, click the Paste icon, or on the Edit menu, click Paste.

    To undo an action in the Script Pane

    Press CTRL + Z or, on the toolbar, click the Undo icon, or on the Edit menu, click Undo.

    To redo an action in the Script Pane

    Press CTRL + Y or, on the toolbar, click the Redo icon, or on the Edit menu, click Redo.

    How to save a script

    An asterisk appears next to the script name to mark a file that hasn’t been saved since it was changed. The asterisk disappears when the file is saved.

    To save a script

    Press CTRL + S or, on the toolbar, click the Save icon, or on the File menu, click Save.

    To save and name a script

    1. On the File menu, click Save As. The Save As dialog box will appear.
    2. In the File name box, enter a name for the file.
    3. In the Save as type box, select a file type. For example, in the Save as type box, select ‘PowerShell Scripts ( *.ps1 )’.
    4. Click Save.

    To save a script in ASCII encoding

    By default, Windows PowerShell ISE saves new script files ( .ps1 ), script data files ( .psd1 ), and script module files ( .psm1 ) as Unicode (BigEndianUnicode) by default. To save a script in another encoding, such as ASCII (ANSI), use the Save or SaveAs methods on the $psISE.CurrentFile object.

    The following command saves a new script as MyScript.ps1 with ASCII encoding.

    The following command replaces the current script file with a file with the same name, but with ASCII encoding.

    The following command gets the encoding of the current file.

    Windows PowerShell ISE supports the following encoding options: ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, UTF8, and Default. The value of the Default option varies with the system.

    Windows PowerShell ISE doesn’t change the encoding of script files when you use the Save or Save As commands.

    In this guide we are going to look at how to use a script and scriptreplay commands in Linux that can help you to record commands and their output printed on your terminal during a given session.

    Record and Replay Linux Terminal Commands

    The history command is a great command-line utility that helps users to store previous command used, though it does not store the output of a command.

    Therefore the script command comes in handy to provide you a powerful functionality that helps you to record everything that is printed on your terminal to a log_file. You can then refer to this file later on in case you want to view the output of a command in history from the log_file.

    You can also replay commands that you recorded using the scriptreplay command by using a timing information.

    How to Record Linux Terminal Using script Command

    The script command stores terminal activities in a log file that can be named by a user, when a name is not provided by a user, the default file name, typescript is used.

    Basic Syntax of script Command

    To start recording of Linux terminal, type script and add the log filename as shown.

    To stop script, type exit and press [Enter].

    If the script can not write to the named log file then it shows an error.

    For example, in the output below, the permissions of the file typescript does not allow reading, writing and execution of the file not by any user or group. When you run the script command without a log file name, it attempts to write to the default file, typescript hence showing an error.

    Examples of using the script command

    I have named my log file script.log in the example below, you can give your file a different name.

    Now try to execute few commands to allow script to record executed commands on the terminal.

    Now try to view the log file ‘script.log‘ for all recorded commands, while you view the log you realize that the script also stores line feeds and backspaces.

    Sample Output

    You may use the -a option to append the log file or typescript, retaining the prior contents.

    View the contents of script, log after using -a option to append it.

    Sample Output

    To log results of a single command other than an interactive shell session, use the -c option.

    If you want script to run in a quiet mode then you can use the -q option. You will not see a message that shows script is starting or exiting.

    To set timing information to standard error or a file use the –timing option. The timing information is useful when you want to re-display the output stored in the log_file.

    Let us start script and run the following commands w, uptime and cal to be recorded.

    You can view the script.log and time.txt file for the timing command above.

    Sample Output

    Now view time.txt file.

    Sample Output

    The time.txt file has two columns, the first column shows how much time has elapsed since the last display and the second column, shows the number of characters that have been displayed this time around.

    Use the man page and –help to seek for more options and help in using the script command-line utility.

    Using scriptreplay to replay scripts using timing information

    The scriptreplay command helps to replay information in your log_file recorded by the script command.

    The timing information is defined by the -timing=file option used with the script command and file in this case is file.txt that was used with script command .

    Remember you need to specify the log_file you used with the script command.

    Let us now replay the last three commands w, uptime and cal that we had run as follows.

    Replay Last Executed Commands in Linux

    When the log_file replayed using the timing information, the commands recorded are run and their output is displayed at the same time the original output was displayed while being recorded.

    Summary

    These two commands, script and scriptreplay easy to use and help a lot when you need to run the same batch of commands several times. They help a lot in managing servers that have only command-line interface for interaction with your system. Hope this guide was useful and if you have anything to add or face a challenge while using them, do not hesitate to post a comment.

    If You Appreciate What We Do Here On TecMint, You Should Consider:

    TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

    If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

    We are thankful for your never ending support.

    Why Viewing Files In Linux Is Important

    Whether you are a regular user or an experienced system administrator, sooner or later, you will need to interact with files in Linux through the command line. For example, you might need to troubleshoot an issue by checking the log files, viewing your system’s details, or even customizing it by editing the configuration files.

    Knowing how to display the contents of a file in Linux can make your life easier and save you time from constantly opening text editors. Many built-in functions make viewing files easy, fast, and tailored to your needs.В

    How to Display Contents of a File in Linux

    The simplest way to view text files in Linux is the cat command. It displays the complete contents in the command line without using inputs to scroll through it.

    Here is an example of using the cat command to view the Linux version by displaying the contents of the /proc/version file.

    Sometimes the information needed is in the first lines of a file. In that case, use the head command to view the first ten lines of a file in Linux. For example, users can display basic information about the CPU used by viewing the beginning of the /proc/cpuinfo file.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Like the tail command, use the -n flag with the head command to display the desired number of lines, starting from the beginning of a given file. For example, head -5 shows the first five lines of a given file.

    While the cat command is helpful when dealing with a small file, it is not the best way to view large log files. The tail command allows viewing the last ten lines of a file by default instead of filling your terminal window with a wall of text, making it the perfect command to use if you want to check the last log entries.

    Here is the output of the tail command.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Flags

    A user can select how many lines the command should display by passing theВ –n flag (where n is an integer). For example, the tail -15 command will output the last 15 lines on a given file.

    Another helpful flag used with the tail command is -f. It outputs the last ten lines of a file by default, but it also keeps displaying new entries as the file is updated. This function is beneficial when viewing the latest updates in log files to troubleshoot an issue. If you only want to use this functionality, you can use the tail -f command, and it will only display the entries that appeared in the file after running the command.

    Another way to view file contents in Linux is the more command. It displays a file in the terminal, one page at a time. While using the more command, the Enter key scrolls through the file line by line, or the Space key scrolls one full screen at a time. Finally, you can close the file by pressing the Q key.

    Here is an example of using more to display the contents of the cpuinfo file in Linux.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    While more is a handy command, it does come with a drawback. After closing a file, its contents stay written in the terminal window, filling it with text, forcing users to either clear the window or scroll back up to find something. It can also be slow, as it loads the entire file though displaying only one page at a time.

    That’s where the less command comes in handy. It’s very similar to more, but with the benefit of not keeping all the text in the terminal window. The less command also comes with a built-in search function, allowing you to highlight the parts of the file for which you are looking. To search with less, press the forward slash key followed by the text you want to search.

    The following is what the search function looks like if we search for /cpu in the cpuinfo file.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Another exciting way to display the contents of a file in Linux is in reverse order. To do so, use the tac command. It is similar to cat but reversed, reading and displaying the file starting from the last line. For example, here is what the output of tac looks like used to display the contents of the cpuinfo file.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    For better readability, pipe the tac command into less to scroll through the file. Users accomplish piping using the desired command, the pipe character, and the other command. The syntax is as follows.

    Here is an example output from this command.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    While not used for displaying the contents of a file, the grep command is handy for filtering the output of commands. For example, grep works for searching for specific text in a file.

    In addition, pipe the output of other commands through grep, narrowing the search to what we are looking for in the file.

    Here is an example of piping the output from the head command into the grep command.

    Conclusion

    While it might seem intimidating at first, learning how to display the contents of a file in Linux will make it significantly easier to navigate through any Linux distribution. These skills save time and make your job easier.

    Do you already know how to display the contents of a file in Linux and just need hosting? Liquid Web has managed hosting options to help you get started with your next project. Contact our sales team to make your purchase.

    Search

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Do you want to create a Shell script in your Linux system?

    This guide will take you through how to create a shell script using multiple text editors, how to add comments, and how to use Shell variables.

    But before heading over to creating a shell script, let’s understand what Shell scripting in Linux is.

    What is Shell Scripting in Linux?

    So, what’s Shell scripting?

    Shell Scripting is defined as an open-source program that’s run by Linux or Unix shell. Through shell scripting, you can write commands to be executed by the shell.

    Lengthy and repetitive commands are usually combined into a simple command script. You can store this script and execute it whenever needed.

    Shell scripting in Linux makes programming effortless.

    Ways of Creating a Simple Shell Script in Linux

    Creating a simple shell script in Linux is very easy. You can do that using multiple text editors. This tutorial will show how to create a shell script with two different methods, such as 1) using the default text editor, and 2) Using the Vim text editor tool.

    Method 1: Using the Default Text Editor

    To create a shell script using the default text editor, just follow the steps given below.

    Step 1: Create a text file having a “.sh” extension. Then type a simple script.

    Step 2: Now don’t change the directory. And open the terminal. Using the command below, give executable access to the file created.

    Step 3: Execute the below-given script in the terminal:

    This was a simple technique of creating a shell script in Linux using the default editor. Now, let’s look at the next method.

    Method 2: Using the Vim Text Editor Tool

    Vim text editor tool is a tool that helps create a shell script in a Linux system. In case you don’t have it already installed, use the command to install Vim:

    Now follow the steps for creating a shell script using the tool.

    Step 1: For opening the editor, simply type:

    Step 2: Once you’re in, open the terminal. Then create a bash file via:

    After the execution of the command, the editor will appear as below.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Step 3: Press “i” from the keyboard and get into the Insert mode. Now, type the following commands in it.

    Step 4: Press “Esc” to exit this mode. Then type “:w” to save your script.

    Once saved, the shell script will appear as below.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Step 5: When you’re back to the console, type “:q”. Then write:

    The above command will execute the shell file and will display the output in the terminal.

    Adding Comments in Shell

    Just like in many other programming languages, we use “#” (the hashtag symbol) to add comments in the shell script.

    In the Vim editor, open the text file. And write a comment as below.

    The above example illustrates the usage of the “#” symbol in adding comments in a shell script.

    Using Shell Variables

    Variables are a value that can store information in the form of numbers and characters. Likewise, Shell variables can store data as well. For example,

    The above lines will create a shell variable “var” and then will print it.

    Let’s write a small script, now.

    To get the value of the variable, execute the command below.

    Let’s write another script using a variable.

    Run the script file and enter the “name” as “Robin”.

    As you enter the input, the script reads the name and replies:

    Then enter the “remark” as “good”. And you’ll notice that the script repeats the remark.

    The second line of the above set of codes shows the response from the script.

    These were some simple shell scripts. You can write advanced scripts containing loops, functions, and conditional statements. Shell scripting will make Linux administration a breeze.

    The Conclusion

    In this article, you have learned to create a simple Shell script. Now you can create your own scripts in Linux following the above-mentioned methods and tips.

    Suparna is a freelance writer who writes about Linux including tips, tricks, and how-tos.

    Since Linux and Mac OS X are *Nix based systems, many commands would work on both platforms. However, some commands may not available on both platforms, for example pbcopy and pbpaste. These commands are exclusively available only on Mac OS X platform. The Pbcopy command will copy the standard input into clipboard. You can then paste the clipboard contents using Pbpaste command wherever you want. Of course, there could be some Linux alternatives to the above commands, for example Xclip. The Xclip utility is similar to Pbcopy. But, the distro-hoppers who switched to Linux from Mac OS would miss this command-pair and still prefer to use them. No worries! This brief tutorial describes how to use Pbcopy and Pbpaste commands on Linux.

    Install Xclip and Xsel in Linux

    Like I already said, Pbcopy and Pbpaste commands are not available in Linux. However, we can replicate the functionality of pbcopy and pbpaste commands using Xclip and/or Xsel commands via shell aliasing. Both Xclip and Xsel packages available in the default repositories of most Linux distributions. Please note that you need not to install both utilities. Just install any one of the above utilities.

    To install them on Arch Linux and its derivatives, run:

    On Debian, Ubuntu, Linux Mint:

    Once installed, you need create aliases for pbcopy and pbpaste commands. To do so, edit your

    If you want to use xclip, paste the following lines:

    If you want to use xsel, paste the following lines in your

    Save and close the file.

    Next, run the following command to update the changes in

    The ZSH users paste the above lines in

    /.zshrc file and update the changes using command:

    Let us see some examples.

    The pbcopy command will copy the text from stdin into clipboard buffer. For example, have a look at the following example.

    The above command will copy the text “Welcome To OSTechNix” into clipboard. You can access this content later and paste them anywhere you want using Pbpaste command like below.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    pbcopy and pbpaste commands in action

    Here are some other use cases.

    I have a file named file.txt with the following contents.

    You can directly copy the contents of a file into a clipboard as shown below.

    Now, the contents of the file is available in the clipboard as long as you updated it with another file’s contents.

    To retrieve the contents from clipboard, simply type:

    You can also send the output of any Linux command to clip board using pipeline character. Have a look at the following example.

    Now, type “pbpaste” command at any time to display the output of “ps aux” command from the clipboard.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    pbpaste command in action

    There is much more you can do with Pbcopy and Pbpaste commands. I hope you now got a basic idea about these commands.

    PowerShell is a great scripting language to write all kinds of scripts. But did you know that you can also download a file with PowerShell? You can use PowerShell to download single or multiple files from the internet.

    There are a couple of methods when it comes to downloading files with PowerShell. We can download files from any URL with PowerShell, local network shares, and from behind credential protected websites.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    In this article, we are going to start with the most straightforward method to download a single file and we are also going to take a look at other (faster) methods to download a file with PowerShell.

    Powershell Download File from URL

    We are going to start with the most common way to download a file from an URL with PowerShell. For this, we will be using the Invoke-WebRequest cmdlet. To download a file we need to know the source URL and give up a destination for the file that we want to download.

    The parameter -OutFile is required. You don’t need to enter the full path, but a file name is required.

    Invoke-WebRequest will overwrite the local file if it already exists without any warning

    Authentication with Invoke-WebRequest

    Some online resources require you to log in before you can access/download the files. With the Invoke-WebRequest cmdlet, we can provide the credentials that are needed for downloading the files.

    If you are creating a script that will need to run automatically, then you will need to store the credentials in the script itself. I recommend creating a secure string password and store it in a text file on the computer that is running the script. It still won’t be super secure, but it’s a little bit better than using a plaintext password in your script.

    Download files faster with Start-BitsTransfer in PowerShell

    The Invoke-WebRequest method is available in all PowerShell versions and can also be used on Linux machines. But the downside is that it’s a bit slow. With Invoke-WebRequest, the file is buffered in the memory first, before it’s written to the disk.

    A faster and better way is to use the Start-BitsTransfer cmdlet in PowerShell. This cmdlet allows you to queue files, set priority (useful for bandwidth limitation), can run in the background and download multiple files asynchronous.

    This is the most basic method of downloading a file with BitsTransfer, you only need a source and destination.

    By default, the download jobs run in the foreground consuming the maximum bandwidth available. You can change this by setting the priority of the job:

    • Foreground – Default
    • High
    • Normal
    • Low

    Only the idle network bandwidth is used when you set the priority to high, normal, or low.

    Another option is to run the download job asynchronous, allowing you to start multiple download jobs at the same time. When you use this method, make sure that you complete the download job when it’s finish.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    As you can see I have downloaded the same bin file as before. But if we look in the destination folder we only see a .tmp file.

    You will need to run Complete-BitsTransfer to finish the download job.

    Downloading Multiple Files with PowerShell

    To download multiple files with PowerShell we first need to know which files are available. We can use the Invoke-WebRequest cmdlet first to get the content from the webpage.

    If you take a look at the content of then you will see a list of binary files that we can download.

    First, we are going to scrape the website

    This will return not only the content of the webpage but also other properties, like Links and InputFields.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    This is a pretty simple webpage, but let’s say we only want the files that start with the name “random”. We can filter the links with a simple like query and select only the href property from each link.

    So we now have the links for all random binary files. All we need to do is download each one of them.

    When you need to download multiple files it’s better to use the Start-BitsTransfer cmdlet. It allows you to download multiple files simultaneously in the background with the parameter -Asynchronous

    Other advantages of the BitsTransfer cmdlet is it can handle connection interruptions and is aware of your network bandwidth usage.

    We can start all the download jobs by using the parameter – Asynchronous . Without it, the BitsTransfer cmdlet downloads the first file completely before starting the next download while putting your script on hold in the meantime.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    You can use the Get-BitTransfer cmdlet to show the progress of the download. If you want to stop the download job then use the Remove-BitTransfer cmdlet. You can stop a single job based on its JobId or all jobs with:

    Complete the BitsTransfer download

    It’s important to complete the transferred file when using BitsTransfer in combination with the Asynchronous parameter. When using Asynchronous it creates a temp file during the download process. But to actually use the file you will need to run the following cmdlet:

    PowerShell Download file from Server

    We won’t be using the Invoke-WebRequest to download files from a local network source, like a server or NAS, with PowerShell. Instead, we can simply use the Copy-Item cmd to download a file from a server.

    The Copy-Items cmdlet takes a source and destination, just like the Invoke-WebRequest cmdlet.

    If you want to know more about the Copy-Item cmdlet, then you should read this article where I explain more about the cmdlet and alternatives.

    Powershell Download Zip File

    The method to download zip files is pretty much the same as a normal file. But I wanted to show you how that downloads and extracts the zip file. This way you can immediately process the files inside the zip file without manual interaction.

    I am going to use this sample csv on GitHub which we can download in a zip file. We have to set a destination for the zip file itself and a path where we want to extract the files to.

    The Invoke-WebRequest downloads the zip file just like any other file.

    The next step is to extract the zip file automatically in the desired location. For this we are going to use a COM object. With the COM object we can extract the zip file and copy the content to the desired location.

    Wrapping Up

    Downloading files with PowerShell is pretty easy when you have the exact URL of the source file. When you need to scrape a website first then it can be a little bit more work to set up properly.

    Try to use the Start-BitsTransfer cmdlet for downloading files and set the priority to normal when using it in an autonouse script. BitsTransfer has more option when it comes to retries, resuming and bandwidth control then Invoke-WebRequest.

    If you have any questions about how you can download a file with PowerShell, then drop a comment below.

    Avoid scrolling and/or save the generated output

    One of the most useful ways to log and troubleshoot the behavior of commands or batch jobs that you run on Windows is to redirect output to a file.

    However, there are a few different ways you can redirect command line writes to a file. The option you choose depends on how you want to view your command output.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    How Windows Command Prompt Output Works

    When you type a command in the Windows console (command prompt), the output from that command goes to two separate streams.

    • STDOUT: Standard Out is where any standard responses from commands go. For example the standard response for the DIR command is a list of files inside a directory.
    • STDERR: Standard Error is where any error messages go if there’s a problem with the command. For example if there aren’t any files in the directory, the DIR command will output “File Not Found” to the Standard Error stream.

    You can redirect output to a file in Windows for both of these output streams.

    Redirect Standard Output Write to New File

    There are two ways you can redirect standard output of a command to a file. The first is to send the command output write to a new file every time you run the command.

    To do this, open the command prompt and type:

    The > character tells the console to output STDOUT to the file with the name you’ve provided.

    When you run this command, you’ll notice that there isn’t any response in the command window except the error that the file doesn’t exist.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    This is because the standard output for the command was redirected to a file called myoutput.txt. The file now exists in the same directory where you ran the command. The standard error output still displays as it normally does.

    Note: Be careful to change the active directory for the command prompt before running the command. This way you’ll know where the output files are stored.

    You can view the standard output that went to the file by typing “myoutput.txt” in the command window. This will open the text file in your default text file viewer. For most people, this is usually Notepad.exe.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    The next time you run the same command, the previous output file will be deleted. A new output file will be recreated with the latest command’s output.

    Redirect Standard Output Writes to the Same File

    What if you don’t want to overwrite the same file? Another option is to use >> rather than > to redirect to an output file. In the case of this example, you would type:

    You’ll see the same output (the error only).

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    But in this case, instead of overwriting the output file, this command appends the new output to the existing output file.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    Every time you run a command and append the output to a file, it’ll write the new standard output to the end of the existing file.

    Redirect Standard Error To a File

    The same way you can redirect standard output writes to a file, you can also output the standard error stream to a file.

    To do this, you’ll need to add 2> to the end of the command, followed by the output error file you want to create.

    In this example, you’ll type the command:

    This sends the standard output stream to myoutput.txt, and the standard error stream to output.err. The result is that no output stream at all gets displayed in the console window.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    However, you can see the error messages by typing output.err. This will open the file in your default text file viewer.

    As you can see, any error messages from the command are output to the error file. Just as with the standard output, you can use >> instead to append the error to errors from previously run commands.

    Redirect All Output Writes to a Same File

    All of the approaches above result in multiple files. One file is for the standard output stream and the other is for the standard error stream.

    If you want to include both of these outputs to the same file, you can do that too. To do this, you just need to redirect all output to the same file using the following command.

    Here’s how this command works:

    • The standard output is directed to the output file identified by output number 1.
    • The standard error output identified by the number 2 is redirected to the output file identified by number 1.

    This will append the error output to the end of the standard output.

    How to save the output of a command to a file in bash (aka the linux and macos terminal)

    This is a useful way to see all output for any command in one file.

    Silencing Standard or Error Output Streams

    You can also turn off either Standard Output or Standard Error by redirecting the output to a NUL instead of a file.

    Using the example above, if you only want Standard Output and no Standard Error at all, you can use the following command:

    This will result in the same output file as the first example above where you only redirected the Standard Output, but with this command the error won’t echo inside the console. It won’t create an error log file either.

    This is useful if you don’t care about any errors and don’t want them to become a nuisance.

    You can perform any of the same output commands above from inside a BAT file and the output from that line will go to the output file you specify. This is a useful way to see whether any commands within a BAT file had any errors when they tried to run.

    Ryan has been writing how-to and other technology-based articles online since 2007. He has a BSc degree in Electrical Engineering and he’s worked 13 years in automation engineering, 5 years in IT, and now is an Apps Engineer. Read Ryan’s Full Bio