How to save entire output of bash script to file

て烟熏妆下的殇ゞ 提交于 2020-01-04 02:18:25

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/17554018/how-to-save-entire-output-of-bash-script-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!