redirecting stdout and stderr to file using bash

0 votes

In order to redirect stdout to a file in bash I use:

cmd > file.txt

To redirect stdout using Bash while appending I use:

cmd >> file.txt

and for both stdout and stderr to a truncated file I use:

cmd &> file.txt

How do I redirect both stdout and stderr appending to a file? cmd &>> file.txt did not work for me

But I want to redirect both stdout and stderr appending to a file. How do I do that?

Mar 19, 2019 in Linux Administration by DragonLord999
• 8,450 points
22,430 views

1 answer to this question.

0 votes
cmd >>file.txt 2>&1

Bash always executes and redirects from left to right:

  1. >>file.txt: simply opens the text file in append mode and puts the stdout there
  2. 2>&1: this redirects stderr to the same place where stdout is ging. which in this case is the file opened in append mode. The &1 is using the descriptor which was being used by stdout
answered Mar 19, 2019 by ajs3033
• 7,300 points

Related Questions In Linux Administration

0 votes
1 answer

How to extract file base name without path and extension in bash?

You don't actually have to call the ...READ MORE

answered May 31, 2019 in Linux Administration by Shubham
• 13,490 points
5,945 views
0 votes
0 answers

Send private message to Discord user using bash and linux AT command

I'm running a Discord bot written in ...READ MORE

Apr 25, 2022 in Linux Administration by Edureka
• 13,690 points
1,302 views
0 votes
1 answer

pipe to clipboard using Bash

Try xclip; xclip - command line interface to ...READ MORE

answered Jun 17, 2019 in Linux Administration by Shubham
• 13,490 points
910 views
0 votes
1 answer

To attach a file using mail command on Linux

$ echo | mutt -a syslogs.tar.gz admin@domain.org READ MORE

answered Jun 28, 2019 in Linux Administration by Upasana
• 8,620 points
2,883 views
0 votes
1 answer
0 votes
1 answer

Redirecting output to a file and stdout

The command you want is named tee; foo ...READ MORE

answered May 31, 2019 in Linux Administration by Shubham
• 13,490 points
1,045 views
0 votes
1 answer
0 votes
1 answer

How do I set variable if a specific package version is installed in CFEngine?

Here is what you can do.Just use packagesmatching to ...READ MORE

answered Jul 12, 2018 in Other DevOps Questions by Atul
• 10,240 points
1,220 views
0 votes
2 answers

how to loop through the content of a file using bash

#!/bin/bash for i in  `cat peptides.txt` do echo $i done READ MORE

answered Sep 5, 2020 in Linux Administration by Prakash K. Aithal
3,034 views
0 votes
1 answer

How to collect all output in one file?

You can use 2> to redirect it: foo ...READ MORE

answered Mar 1, 2019 in Linux Administration by ajs3033
• 7,300 points
1,034 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP