user3406590
user3406590

Reputation: 11

How to capture shell script output

I have an unix shell script. I have put -x in shell to see all the execution step. Now I want to capture these in one log file on a daily basis. Psb script.

#!/bin/ksh -x   
Logfile= path.log.date    
Print " copying file" | tee $logifle     
Scp  -i key source destination | tee -a $logfile.    
Exit 0;

Upvotes: 1

Views: 6658

Answers (3)

ULick
ULick

Reputation: 999

I would prefer to explicitly redirecting the output (including stderr 2> because set -x sends output to stderr).

This keeps the shebang short and you don't have to cram the redirecton and filename-building into it.

#!/bin/ksh
logfile=path.log.date
exec >> $logfile 2>&1  # redirecting all output to logfile (appending)
set -x               # switch on debugging
# now start working
echo "print something"

Upvotes: 0

iamauser
iamauser

Reputation: 11469

There are two cases, using ksh as your shell, then you need to do IO redirection accordingly, and using some other shell and executing a .ksh script, then IO redirection could be done based on that shell. Following method should work for most of the shells.

$ cat somescript.ksh
#!/bin/ksh -x

printf "Copy file \n";
printf "Do something else \n";

Run it:

$ ./somescript.ksh 1>some.log 2>&1

some.log will contain,

+ printf 'Copy file \n'
Copy file 
+ printf 'Do something else \n'
Do something else 

In your case, no need to specify logfile and/or tee. Script would look something like this,

#!/bin/ksh -x      
printf "copying file\n"    
scp -i key user@server /path/to/file   
exit 0

Run it:

$ ./myscript 1>/path/to/logfile 2>&1

2>&1 captures both stderr and stdout into stdout and 1>logfile prints it out into logfile.

Upvotes: 0

GopiGowtham
GopiGowtham

Reputation: 71

First line of the shell script is known as shebang , which indicates what interpreter has to be execute the below script.

Similarly first line is commented which denotes coming lines not related to that interpreted session.

To capture the output, run the script redirect your output while running the script.

ksh -x scriptname >> output_file 

Note:it will output what your script's doing line by line

Upvotes: 1

Related Questions