bash: How to send the output to a file upon users' request?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting bash: How to send the output to a file upon users' request?
# 1  
Old 04-08-2012
bash: How to send the output to a file upon users' request?

Let's say I have a script which creates a report. I use
Code:
getopts

to have different options available to the user. One of these options is -f which basically exports the output of script to a text file which user may give the name of that text file. How can I output the result to the requested file.
An example of my code is here:

Code:
#!/bin/bash

resetTime=1
mytotalTime=0
totalHour=0
totalMin=0
averagemem=0
finalaverage=0
times=0
function usage
{
    cat << EOF
    USAGE: $0 [options] file
EOF
}

function usageOption
{
    cat << EOF
    $0 Must select report type: -u(ser) or -c(ommand)
EOF
}

function displayTime
{
    awk -F"," '/'$user'/{print $7}' $file > /tmp/mytotalTime.$USER
    cat /tmp/mytotalTime.$USER | while read resetTime;
    do
        Min=$(echo $resetTime | cut -d ":" -f2)
        Hour=$(echo $resetTime | cut -d ":" -f1)
        totalHour=$((totalHour+Hour))
        echo $totalHour > /tmp/totalHour.$USER
        totalMin=$(echo "($totalMin+$Min)" | bc)
        echo $totalMin > /tmp/totalMin.$USER
    done
    totalHour=$(cat /tmp/totalHour.$USER)
    totalMin=$(cat /tmp/totalMin.$USER)
    mytotalTime=$(echo "($totalHour*60+$totalMin)" | bc)
    totalHour=$(echo "($mytotalTime/60)" | bc)
    totalMin=$(echo "($mytotalTime%60)" | bc)
    echo -e "TOTAL RUNNING TIME:    " $totalHour":"$totalMin "\n"
}

if [ $# -eq 0 ]; then
    usage
    exit 1
fi

pflag=
user=""
command=
fileName=
totalTime=
memoryUse=
priority=
OPTIND=1    # Reset in case getopts has been used previously in the shell

while getopts "u:c:f:tmp" opt;do
 case $opt in
    u)    user=$OPTARG;[ OPTIND=${OPTIND} ];uflag=$user;;
    c)    mycommand=$OPTARG;[ OPTIND=${OPTIND} ]; echo $OPTIND;;
    f)    fileName=$OPTARG;echo "$fileName";[ OPTIND=${OPTIND} ]; echo $OPTIND;;
    t)    totalTime=$OPTARG;[ OPTIND=${OPTIND} ]; echo $OPTIND;;
    m)    memoryUse=$OPTARG;echo "$memoryUse";[ OPTIND=${OPTIND} ];;
    p)    pflag=1;  [ OPTIND=${OPTIND} ];;
    \?)    usage;exit 1;;
    *)        echo -e "\nOption -$OPTARG requires an argument.\n";exit 1;;
 esac
done
shift $(($OPTIND - 1))

# Check for proper number of command line args.

EXPECTED_ARGS=1
#E_BADARGS=65

if [ $# -ne $EXPECTED_ARGS ]; then
    usage
    exit 1
 #exit $E_BADARGS
fi

if [ -n "$user" ] && [ -n "$mycommand" ]; then
    usageOption
    exit 1

elif [ ! -f $1 ]; then
    usage
    exit 1
elif [ $# -ge 2 ]; then
    usage
    exit 1
elif [ -z "$user" ] && [ -z "$mycommand" ]; then
    usageOption
    exit 1
fi

file=$1

if [  -n "$user" ]
then
    printf "\nTOP ANALYSIS REPORT\n"
    printf "\nName: %4s\n" $user

    if [ $pflag  ]; then        ###
        echo "-------------------------------------------------------------------------------------------------"
        printf "| %-15s | %-23s | %-10s | %-10s | %-10s | %-10s |\n" "USER" "PROCESS" "PROC ID" "% CPU" "% MEM" "PRIORITY"
        echo "|-----------------+-------------------------+------------+------------+------------+------------|"
        awk -F"," '/'$user'/ { printf "| %-15s | %-23s | %-10s | %-10s | %-10s | %-10s |\n", $2, $3, $1, $5, $6, $4 }' $file
        echo "-------------------------------------------------------------------------------------------------"
    else
        echo "------------------------------------------------------------------------------------"
        printf "| %-15s | %-23s | %-10s | %-10s | %-10s |\n" "USER" "PROCESS" "PROC ID" "% CPU" "% MEM"
        echo -e "|-----------------+-------------------------+------------+------------+------------|"
        awk -F"," '/'$user'/ { printf "| %-15s | %-23s | %-10s | %-10s | %-10s |\n", $2, $3, $1, $5, $6 }' $file
        echo -e "------------------------------------------------------------------------------------"
   fi
fi

Thank you!
# 2  
Old 04-08-2012
If you want to redirect all of standard output to the file, then adding this will do just that provided that the user entered the -f option:

Code:
if [ -n "$fileName" ]
then
    exec >$fileName
fi

Standard error will be left to the tty device.

Probably the best place to put this is right after you assign file=$1

Last edited by agama; 04-08-2012 at 06:11 PM.. Reason: clarification
# 3  
Old 04-08-2012
But this way all goes to the file and there won't be anything on the screen. I want to have my regular report shows up on my terminal and export a copy of that to a file as well when user uses -f option.
I think it works like "tee" if I don't make a mistake.

By the way you are a genius agama
# 4  
Old 04-08-2012
Ok, misunderstood.

Put your 'work' into a function, and then as you said, use tee. This is from the code I cut/pasted a few posts ago, so it might not be what you are working with, but it shows what I mean. I put the 'work' function up front, and put the use of tee in bold at the bottom.

Code:
#!/bin/bash

function do_work
{
        if [  -n "$user" ]
        then
            printf "\nTOP ANALYSIS REPORT\n"
            printf "\nName: %4s\n" $user

            if [ $pflag  ]; then        ###
                echo "-------------------------------------------------------------------------------------------------"
                printf "| %-15s | %-23s | %-10s | %-10s | %-10s | %-10s |\n" "USER" "PROCESS" "PROC ID" "% CPU" "% MEM" "PRIORITY"
                echo "|-----------------+-------------------------+------------+------------+------------+------------|"
                awk -F"," '/'$user'/ { printf "| %-15s | %-23s | %-10s | %-10s | %-10s | %-10s |\n", $2, $3, $1, $5, $6, $4 }' $file
                echo "-------------------------------------------------------------------------------------------------"
            else
                echo "------------------------------------------------------------------------------------"
                printf "| %-15s | %-23s | %-10s | %-10s | %-10s |\n" "USER" "PROCESS" "PROC ID" "% CPU" "% MEM"
                echo -e "|-----------------+-------------------------+------------+------------+------------|"
                awk -F"," '/'$user'/ { printf "| %-15s | %-23s | %-10s | %-10s | %-10s |\n", $2, $3, $1, $5, $6 }' $file
                echo -e "------------------------------------------------------------------------------------"
           fi
        fi

}
# ------------------------------------------------
resetTime=1
mytotalTime=0
totalHour=0
totalMin=0
averagemem=0
finalaverage=0
times=0
function usage
{
    cat << EOF
    USAGE: $0 [options] file
EOF
}

function usageOption
{
    cat << EOF
    $0 Must select report type: -u(ser) or -c(ommand)
EOF
}

function displayTime
{
    awk -F"," '/'$user'/{print $7}' $file > /tmp/mytotalTime.$USER
    cat /tmp/mytotalTime.$USER | while read resetTime;
    do
        Min=$(echo $resetTime | cut -d ":" -f2)
        Hour=$(echo $resetTime | cut -d ":" -f1)
        totalHour=$((totalHour+Hour))
        echo $totalHour > /tmp/totalHour.$USER
        totalMin=$(echo "($totalMin+$Min)" | bc)
        echo $totalMin > /tmp/totalMin.$USER
    done
    totalHour=$(cat /tmp/totalHour.$USER)
    totalMin=$(cat /tmp/totalMin.$USER)
    mytotalTime=$(echo "($totalHour*60+$totalMin)" | bc)
    totalHour=$(echo "($mytotalTime/60)" | bc)
    totalMin=$(echo "($mytotalTime%60)" | bc)
    echo -e "TOTAL RUNNING TIME:    " $totalHour":"$totalMin "\n"
}

if [ $# -eq 0 ]; then
    usage
    exit 1
fi

pflag=
user=""
command=
fileName=
totalTime=
memoryUse=
priority=
OPTIND=1    # Reset in case getopts has been used previously in the shell

while getopts "u:c:f:tmp" opt;do
 case $opt in
    u)    user=$OPTARG;[ OPTIND=${OPTIND} ];uflag=$user;;
    c)    mycommand=$OPTARG;[ OPTIND=${OPTIND} ]; echo $OPTIND;;
    f)    fileName=$OPTARG;echo "$fileName";[ OPTIND=${OPTIND} ]; echo $OPTIND;;
    t)    totalTime=$OPTARG;[ OPTIND=${OPTIND} ]; echo $OPTIND;;
    m)    memoryUse=$OPTARG;echo "$memoryUse";[ OPTIND=${OPTIND} ];;
    p)    pflag=1;  [ OPTIND=${OPTIND} ];;
    \?)    usage;exit 1;;
    *)        echo -e "\nOption -$OPTARG requires an argument.\n";exit 1;;
 esac
done
shift $(($OPTIND - 1))

# Check for proper number of command line args.
EXPECTED_ARGS=1
#E_BADARGS=65

if [ $# -ne $EXPECTED_ARGS ]; then
    usage
    exit 1
 #exit $E_BADARGS
fi

if [ -n "$user" ] && [ -n "$mycommand" ]; then
    usageOption
    exit 1

elif [ ! -f $1 ]; then
    usage
    exit 1
elif [ $# -ge 2 ]; then
    usage
    exit 1
elif [ -z "$user" ] && [ -z "$mycommand" ]; then
    usageOption
    exit 1
fi

file=$1

if [ -n "$fileName" ]
then
    do_work | tee $fileName
else
    do_work
fi



Quote:
By the way you are a genius agama
Thanks, but I'm afraid I'm just a regular guy with a wee bit of experience.
This User Gave Thanks to agama For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

About adding users from a text file using bash

hello, I try to add users from a text file with this form: username:groupename:homedir first i extract data which is separated by ":" then i use useradd to add users/groups. but,,, my code doesn't works : #!/bin/bash echo "give me a text file: " read dir # control if... (2 Replies)
Discussion started by: ref012
2 Replies

2. Shell Programming and Scripting

Send mdfind output into script file

I'm using mdfind to list images according to their orentation, thus:- mdfind " kMDItemOrientation == 1" -onlyin "/Users/me/Documents/STUDY/AskForum" which outputs /Users/me/Documents/STUDY/AskForum/01 (5).jpg /Users/me/Documents/STUDY/AskForum/01 (4).jpg... (3 Replies)
Discussion started by: waggs
3 Replies

3. Shell Programming and Scripting

Bash script to send lines of file to new file based on Regex

I have a file that looks like this: cat includes CORP-CRASHTEST-BU e:\crashplan\ CORP-TEST /usr/openv/java /usr/openv/logs /usr/openv/man CORP-LABS_TEST /usr/openv/java /usr/openv/logs /usr/openv/man What I want to do is make three new files with just those selections. So the three... (4 Replies)
Discussion started by: newbie2010
4 Replies

4. UNIX for Advanced & Expert Users

shell script to send separate mails to different users from a text file

Hi Friends, Could you guys help me out of this problem... I need to send an email to all the users and the email has to be picked from the text file. text file contains the no. of records like: Code: giridhar 224285 847333 giridhar276@gmail.com ramana 84849 33884... (0 Replies)
Discussion started by: giridhar276
0 Replies

5. IP Networking

How to send non get request from linux server

Hi I want to send non get request for HTTP from linux server. Please let me knwo how to do that Thanks Lakshmikant (0 Replies)
Discussion started by: lakshmikant
0 Replies

6. UNIX for Dummies Questions & Answers

how to send an xml request

I'm new to Unix and web development but I'm in need to send an xml request to a web server Ican't find an easy way to do it from the command line, if somebody can help me with a sample would be amazing! my Unix says that curl is not installed so i was wondering if there is another way to test... (1 Reply)
Discussion started by: mpoblete
1 Replies

7. Shell Programming and Scripting

bash: How to send a file/directory as argument?

Hi, I'd like to make a script where I can send a directory OR files as an argument, and compress them. My proble mis, I do know how to send a directory, but I do not know what to do if there are more than 1 file, I mean I can store the directory in $1, but how do I store 4 files? must I write $1,... (3 Replies)
Discussion started by: lamachejo
3 Replies

8. Shell Programming and Scripting

How to send XML data using HTTP Post Request

How to hit HTTP Post Request along with sending XML data to a Remote server through command line utility like wget (or anything else). (0 Replies)
Discussion started by: sandeep reddy
0 Replies

9. Shell Programming and Scripting

capture output of file and send last string thereof to new file

Hello, If I run a program from within shell, the output is displayed in the command line terminal. Is there a way I can capture that output and choose only the very last string in it to send it to a new file? Thank you (6 Replies)
Discussion started by: Lorna
6 Replies

10. UNIX for Dummies Questions & Answers

How to send a Head Http request from command line

Ok. I'm testing a new program component that is supposed to speed up our pipeline on the server. What it does is take in HEAD requests and shuffle them off to a different pipeline that is specially designed to handle HEAD requests quickly. The functionality works but now comes the question: how... (3 Replies)
Discussion started by: darkling235
3 Replies
Login or Register to Ask a Question