How redirect script output from inside of script?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting How redirect script output from inside of script?
# 1  
Old 06-24-2008
How redirect script output from inside of script?

Is it possible to redirect a script output by command inside of that script?

I mean, if I have a script 'dosome.sh' I could run it by
Code:
>dosome.sh > dosome.log

I would dream to get some command inside of scrip to do the same; so, running the dosome.sh would have all output redirected to a log file

(Do not advise, please, put redirection to a log file from every command of that script. It is already unrealistical.)
So I would image something like that:
Code:
#! /usr/bin/bash
 
<redirection command>

....
.... script body
....
# end of script

Iven would be greate to be able to do it the same as it would be done with 'tee' command: to have the output be written to file and in the same time to standard output, to screen, like in this command:
Code:
>dosome.sh | tee dosome.log

Appreciate any advice!
# 2  
Old 06-24-2008
Use exec

I could do that with "exec", but I couldn't get that work to write to a file and stdout simultaneously,

Here is the snippet,

Code:
#!/bin/bash
exec 1>/tmp/log
log() {
 echo `date` : "$@"
}
log "Start"
echo "Process"
ls -l
log "Done Logging"

Please try exec options,

Thanks,
Nagarajan G
# 3  
Old 06-24-2008
Quote:
Originally Posted by ennstate
I could do that with "exec", but I couldn't get that work to write to a file and stdout simultaneously,

...

Please try exec options,

Thanks,
Nagarajan G
Thank you Nagarajan G!!
Exec works perfect to redirect from inside!

I try to get the print-out simultaneously and trying to do it with 'tail -f'

And I've get rock-n-roll:
to start 'tail' need and continue - need to run tail background (... & )
to stop 'tail' when it is done - need to know it's PID
but it is bad idea to kill 'tail' on end of screept - it could exit in a midle
so need to run monitoring of the script to stop the tail rigt after t'tail' start

Is this seems doable? Because by now I have some problem to get PID and kill it. (Actually I did it from outside script and get mess with PIDs)

Any oppinion?
# 4  
Old 06-25-2008
Using exec & pipe

Hi,
I managed to get that working using exec & pipes.The following is the script which i hope to work for you as well,

Code:
#!/bin/bash
#Objective : To redirect the stdout & stderr to two different files from within the script and without sacrificing the scripts output

mkfifo /tmp/out.pipe /tmp/err.pipe

exec 3>&1 4>&1

tee /tmp/std.out < /tmp/out.pipe >&3 &
pid_out=$!
exec  1>/tmp/out.pipe

tee /tmp/std.err < /tmp/err.pipe >&4 &
pid_err=$!
exec  2>/tmp/err.pipe

log() {
 echo "`date` : $@ "
}

log "Starting the process"
log "Listing directories now..."
ls -l
ls -l Log_to_Stderr
exec 1>&3 3>&- 2>&4 4>&-
wait $pid_out
wait $pid_err
rm /tmp/out.pipe /tmp/err.pipe
log "End of Processing"

Please let us know if you could find a better approach

Thanks
Nagarajan G
This User Gave Thanks to ennstate For This Post:
# 5  
Old 06-25-2008
Quote:
Originally Posted by ennstate
Hi,
I managed to get that working using exec & pipes.The following is the script which i hope to work for you as well,
....
Please let us know if you could find a better approach

Thanks
Nagarajan G
Once again, thank you very much for answering and for your time and effort!
Your solution is very interesting, although it is over my knowledge. I will review it in detail tomorrow.
By now I have briefly tried to execute it. It is works, but I do not get where are resulting log files.
I've did commented the 'rm ..' command, but those /tmp/ file are pipes (that I do not understand well, but tomorrow..) and after process is done they are 0-size.

I also have get something to work, but my code is far bigger and I did not take care the error-stream.
I've prepared a peace of code that should be added to the beginning of a script.
One benefit, it seems, it has (if I did not mis-understand your code completely,) that it does not require a script to reach the end. The script could exit in the meddle or could be killed or stopped by any other way.

This is what I have:
Code:
#! /usr/bin/bash
shopt -s expand_aliases
alias ec=/usr/bin/echo

typeset log_fl=`basename $0`_` date +'%H%M%S'`.log
  # sending this script output to the log file
exec 1>${log_fl}

terml=`tty`; 
if [ -z "`ec $terml|grep "/dev/"`" ] 
  then terml=""; 
fi; # if 'tty' returns not a device make it empty

ec "  === output terminal is : >$terml< === ";
ec "  === current script PID=$$ === "
ec "  === log file is \n$log_fl === "

  # starting to print on screen the ${log_fl}  - must be killed by the end of the script
if [ -z ${terml} ]; then
  tail -f ${log_fl} # not sure there is a situation to see the log file in this case
else
  tail -f ${log_fl}>${terml} & 
fi




  # this function will be waiting the script completion and kill the 'tail -f ..'
watch_tail()
{
  alias ec=/usr/bin/echo
  out_dv=$1;  # first parameter is a current proces's terminal, if presented

    # to print out info depending on sent 'out_dv'; - parameters are message
  out()
  {
    inf="\n////-- FROM tail-watcher: ---////\n";
    inf=$inf"            $*"
    inf=$inf"\n\\\\\\\\\\\\\\\\-- FROM tail-watcher  ---\\\\\\\\\\\\\\\\\n"
    if [ -z "$out_dv" ]; then ec "$inf"; else ec "$inf" > ${out_dv}; fi
  }
    # looking for PID of this process only, with PPID=$$ - this process PID
  cur_pid=$$;  # PID of the current process - will be a second number in next 'ps..'

    #the 'ps ' command use first 79 characters of command to display arguments in 'ps .. -o args'
  tail_args=`ec "tail -f ${log_fl}"|cut -c1-79`

    # the 'tail ..''s PID is:
  pid=`ps -e -o pid,ppid,args |\
         grep ${cur_pid} |\
         grep "${tail_args}"|\
         grep -v grep | nawk '{print $1}'`

  if [ "$pid" = "" ]; then
    out " == ${tail_args} is not running";
      # if runing in interactive shell (from screen) - return, else - exit
    if [ -z "$PS1" ]; then exit 0; else return 0; fi
  else 
    out "===>> current 'tail -f ..' PID=$pid";
  fi

  ppid=2; # initialize to get the loop run, at least, once
    # ppid = 1 is 'root' user ; that means the parent (this script) is completed
  while [ "$ppid" != "1" ];do
     let fz++;  # fuze - to break after number of loops in any case (15 sec for 100)
     if ((fz>=8000)); then out "\n\nbreaking the tail-watch loop by fuse \n\n"; break; fi

     pids=`ps -e -o pid,ppid,args  |\
             grep "${tail_args}"|\
             grep ${pid}           |\
             grep -v grep | nawk '{print $1"-"$2}'`;
     if [ "$pids" = "" ]; then 
       out "\n\nbreaking the tail-watch loop by not founding the 'tail..'\n\n"; 
       break; 
     fi; # the 'tail ..' is disapeared; ending loop

     ppid=`ec ${pids} | nawk -F- '{print $2}'`
     if ((ppid==1)); then

       out "killing the tail -f; pid=$pid";
         # wait couple second to give the tail complete output
       sleep 3;
       kill -9 $pid;

     fi
  done
}
  # now starting this one background and, after that, processing the script actions
watch_tail $terml &

I will appreciate your oppinion and advice regarding that.
Alex
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Redirect script output to a file and mail the output

Hi Guys, I want to redirect the output of 3 scripts to a file and then mail the output of those three scripts. I used below but it is not working: OFILE=/home/home1/report1 echo "report1 details" > $OFILE =/home/home1/1.sh > $OFILE echo... (7 Replies)
Discussion started by: Vivekit82
7 Replies

2. Shell Programming and Scripting

How to redirect the output of a command inside ftp block?

hi, i am using ftp to get files from remote server. inside the ftp i want to us ls -ltr command and send the output of it to a file. ftp -n remote_server <<_FTP quote USER username quote PASS password prompt noprompt pwd ls -ltr get s1.txt bye _FTP i... (4 Replies)
Discussion started by: Little
4 Replies

3. Programming

How to redirect the output of a shell script to a file?

hi, i have a html form which call a perl program, this perl program calls a shell script. <html> <head> <title>demo</title> </head> <body> <form name="frm1" action="/cgi-bin/perl_script.pl" method="post"> <input type="text" name="fname"> ... (1 Reply)
Discussion started by: Little
1 Replies

4. Shell Programming and Scripting

script to mail monitoring output if required or redirect output to log file

Below script perfectly works, giving below mail output. BUT, I want to make the script mail only if there are any D-Defined/T-Transition/B-Broken State WPARs and also to copy the output generated during monitoring to a temporary log file, which gets cleaned up every week. Need suggestions. ... (4 Replies)
Discussion started by: aix_admin_007
4 Replies

5. Solaris

Script redirect command output failed, why?

Hi, I put a for loop in a script to eject backup tapes from the robot. The command echo' output goes to the log file without problem, but command vmchange's output does not go to the log file although it's working fine. It still displays on the screen. I've tried '2>&1 1>$log', but nothing changed.... (5 Replies)
Discussion started by: aixlover
5 Replies

6. Shell Programming and Scripting

Redirect the output in shell script for tftp

I've been using tftp in one of my file #!/bin/bash filename1="config1h.txt" filename2="config15.txt" hostname="test.com" tftp $hostname <</dev/null get $filename1 get $filename2 quit EOF My output looks like this # ./test3.sh tftp> Received 1262 bytes in 0.0 seconds tftp> Received... (2 Replies)
Discussion started by: LavanyaP
2 Replies

7. Programming

Redirect input and output to a shell script?

Dear All: I am trying to do something that (I thought) was relatively straightforward, but my code snippet does not seem to work. Any suggestions? Thank you Sincerely yours Misha Koshelev #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include... (0 Replies)
Discussion started by: misha680
0 Replies

8. Shell Programming and Scripting

Redirect bg process output to within the script

Hi, I have a process running in the background, which throws up some output to the terminal when I run my script. How can I read this output from my script? Thank you. (5 Replies)
Discussion started by: Theju
5 Replies

9. Shell Programming and Scripting

how to redirect the output of a grep command to a file inside a shell script

hi, i wat to get the output of a grep command in a file. but when i am trying out the same grep command in the unix prompt its working fine.. i am getting the output properly.. but when i am writing the same command inside my shell script , its just creating a new output file with no contents... (11 Replies)
Discussion started by: kripssmart
11 Replies

10. Shell Programming and Scripting

Script that Redirect SSH output via cron

Hi, I have a script that's being called via a crontab which is a wrapper script that creates a log for the script that gets executed. Within the script that gets executed, it also run's subscripts. I've been able to get everything to work .. but the issue is one of the subscript that goes out... (4 Replies)
Discussion started by: primp
4 Replies
Login or Register to Ask a Question