Buzkie
Buzkie

Reputation: 859

Redirect output of shell script to a file

I'm trying to redirect the output of my script and it needs to be called inside the script.

filename=uname -a
filename="$filename" date

2>&1 | tee $filename".txt"

That is what I have so far, but it's obviously wrong. I don't know too much SH scripting, so help is appreciated

-Alex

Upvotes: 0

Views: 4551

Answers (3)

dubiousjim
dubiousjim

Reputation: 4802

filename=uname -a
filename="$filename" date

2>&1 | tee $filename".txt"

... If you look at the code I posted above I'm trying to dynamically name the log and use tee to print to both the console and the command line.

I think you're looking for something like this:

filename="$(uname -n)-$(date +%F).txt"
{
  dostuff
  domorestuff
} 2>&1 | tee "$filename"

Upvotes: 5

ghostdog74
ghostdog74

Reputation: 342273

its wrong because you are not assigning your variables properly. Assuming date is GNU date, and not some "date" function you created. you might be looking for. Use $() syntax to execute commands and put to variable.

filename="$(uname -a)$(date)"

By the way, are you sure you want to use uname -a for filename ? you might also want to consider formatting your date like date +%Y%m%d-%H%m%s for example.

Upvotes: 1

Konrad Garus
Konrad Garus

Reputation: 54005

You should just print everything to console with echo. Then you can redirect that to a log. For example:

# my_file.sh
echo "Doing stuff"
# Do stuff

# Invocation:
my_file.sh > my_log.log

This gives you the most flexibility and elegance.

You can also write to log directly from script, like:

# my_file.sh
echo "Doing stuff" > my_log.log
# Do stuff

Upvotes: 0

Related Questions