How to Echo Bash Command to a File


If you want to save the output of a command to a file, then you can make use of the redirection operators.


Redirection Operators:

    Operator Description
    > It redirects standard output to a file. Note that it will overwrite the file's content if it exists.
    >> It redirects standard output to a file. Note that it will append the output to the end of the file.
    < It redirects standard input from a file by providing input to a command from the contents of the file.
    2> It redirects standard error (file descriptor 2) to a file, overwriting the file's content if it exists.
    2>> It redirects standard error (file descriptor 2) to a file, appending the output to the end of the file.
    &> It redirects both standard output and standard error to a file, overwriting the file's content if it exists.
    &>> It redirects both standard output and standard error to a file, appending the output to the end of the file..
    >& Redirects one file descriptor to another file descriptor. For example, 2>&1 redirects standard error to standard output.

Note: If the file does not exist the redirection will create one for you.


Now let us see a few simple examples of how to redirect a bash command output to a file.

bash-3.2$ ls -ltrh > /Users/c2ctechtv/Desktop/ls_command_output.txt

bash-3.2$ cat /Users/c2ctechtv/Desktop/ls_command_output.txt
total 0
drwxr-xr-x    5 root  wheel   160B Aug  5 11:51 standalone
drwxr-xr-x   42 root  wheel   1.3K Aug  5 11:51 share
drwxr-xr-x  229 root  wheel   7.2K Aug  5 11:51 sbin
drwxr-xr-x  357 root  wheel    11K Aug  5 11:51 libexec
drwxr-xr-x   32 root  wheel   1.0K Aug  5 11:51 lib
drwxr-xr-x  981 root  wheel    31K Aug  5 11:51 bin
lrwxr-xr-x    1 root  wheel    25B Aug  5 11:51 X11R6 -> ../private/var/select/X11
lrwxr-xr-x    1 root  wheel    25B Aug  5 11:51 X11 -> ../private/var/select/X11
drwxr-xr-x    5 root  wheel   160B Aug 11 07:36 local
Example - bash command output to a file

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap