Sunday, June 30, 2013

2. Batch Files, Redirecting Input/Output, Command Lines Arguments to batch file



 Redirection operators/ Redirecting Input/Output
 < operator means take input from whatever follows e.g. sort < file.dat
 > redirects the output
 >> appends the output to a file
 |  is called pipe, gives output of one command as input to the next command. e.g. 

type  abc.txt | more   
would take output form the type command and will give it to the more command



Standard Input/Output/Errors

-When system boots up, default input is keyboard, default output is display screen. But its important to notice there is one more type of entity called the standard 'errors'. By default errors are directed to output.  
- Symbol ">" directs the standard-out but not the error. So if a command has error even though you are using > operator output wont go to file.
Try this, make sure file1.txt exists.
dir file1.txt > out.txt

Now type a file name which does not exists
dir file_not_found.txt > out.txt 

In this case you will still see some message "File Not found" printed on screen. That is error being directed to standard error.

In DOS numbers are assigned to all input/output/errors as below:
0 = standard input
1 = standard out
2 = standard Error

I you want to direct standard errors to a file you can do this
2>&1

You can try "File Not found " again with below command


dir file_not_found.txt > out.txt 2>&1

 This time you would notice that "File Not Found" message is pushed to out.txt. Hence you have successfully directed standard error to a standard out, which is already directed to a file.



 Command Line Arguments to a Batch File
You can always provide command line argument to batch file
mybat.bat Hello 1 2 
 if your provide parameters to the batch file, in side batch file %1 represent first argument %2 second etc. 
in mybat.bat you can do following  

type %1  :: would print Hello
type %2   :: would print 1 etc.

No comments: