0

I'm writing a very simple bash script that concats two files together and saving output into a log file

#!/bin/bash

file1="/srv/users/test/foo.txt"
file2="/srv/users/test/bar.txt"
newFile="/srv/users/test/foobar.txt"
logFile="/srv/users/test/log.txt"

echo "making file" >> $logFile
echo `date` >> $logFile

cat $file1 $file2 > $newFile 2>> $logFile

echo "finished making file" >> $logFile

But the problem is that if newFile does not exist, then an error is printed to the display rather than to the log file.

How can I make it so the error is printed to the log file instead of the display?

Thanks!

2
  • 1
    "echo `date` >> $logFile" ? Just date >> $logfile.. then an error is printed Please post the exact error message. If newfile does not exists, the > should create it, unless the directory does not exists. Commented Apr 27, 2021 at 19:53
  • @KamilCuk yes the directory also did not exist. Here's the error: /usr/bin/combineCerts: line 11: /absolute/path/foobar.txt: No such file or directory Commented Apr 27, 2021 at 20:15

1 Answer 1

1

Redirect the whole shell stderr instead of one command. Like:

{
   stuff
} 2>>"$logfile"

{ cat $file1 $file2 > $newFile; } 2>> $logFile

check your scripts with http://shellcheck.net

Sign up to request clarification or add additional context in comments.

3 Comments

Ok I was trying to use ` chars when I should have beening using { and }. Thanks!
This worked and was just what I needed. I also learned that the space before and after the curly bracket, and the semi colon, where required
The space between ; and } is not needed.. :p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.