3

I am trying to get the entire output of a bash script to save to a file. I currently have one argument (ip address) at the beginning of the code looks like this:

#!/bin/bash

USAGE="Usage: $0 [<IP address>]"

if [ "$#" == "0" ]; then
        echo "$USAGE"
        exit 1
fi
ip_addr=$1

What I'd like to do is add another argument called "output", that the entire output of the script will save to. I'm aware I could just run myscript.sh | tee textfile.txt, but I'd like to make the script a little easier to run for others.

Thanks in advance,

hcaw

hcaw
  • 93
  • 2
  • 7

1 Answers1

5

After the usage message, add the following line:

exec > "$2"

This will redirect standard output for the rest of the script to the file named in the 2nd argument.

Then run using

myscript 192.0.2.42 output.txt
chepner
  • 497,756
  • 71
  • 530
  • 681
  • @hcaw You can hard code the name of the output file (as in your question to "textfile.txt"), so user won't need to give an extra command line argument. – Sagar Rakshe Jul 09 '13 at 17:16