BAT script written some tips

I had always thought that bat like Linux shell can not set the same function and calls, in fact, I found this to be possible. However, because of the characteristics of the batch is executed line by line, the function of this label must be written in the final text. If you write a batch command earlier, bat will run inside the command line by line. Written in the last side of a document, and skips the code before the "function area."

(By the way Tucao about, written and linux shell of this function is very different, function shell in the command must be written on the front of the command shell to run a line by line, to be called people in the back command.)


Function wording:

:: In this example, I'm trying to write a function named testfunction, its operation is to run a command echo.

:: use the call command, and write the function name in the back, in front of a function name written: This is representative of a label.

call :testfunction



:: The goto command allows the batch to skip part of all functions at run time.

goto EOF


:: the following line from the beginning of the function, they should be the last part of the bat script, in theory, you should not write any of the commands below. First, as the goto command, first of all you have to write a lable

:testfunction

echo Test function is running.

rem exit / b allow the program to jump to the command function is called, rather than directly exit the program.

exit /b


:EOF

All contents :: These are sample scripts.


Of course, you can not write content to function in this bat, but rather another write a bat file, and then call the absolute path of the bat, that is also possible. For convenience I will temporarily call the name of the script I run to a.bat, but the script calls for b.bat.

a.bat content yes.

set a=aaa

call b.bat

echo% b%

pause

The content is b.bat

echo% to%

set b=bbb

In both scripts a script and b each script defines a variable, but does not define another variable defined in the script, but the echo of the other variable is defined in the script of each other. If only a single script, two scripts echo command is not returning any content. But if you run a script and calls b script can be found, the script call variable between calls, they can communicate. However, goto the label can not be exchanged between the scripts that you can not goto to a label b is in a script to go.

But can not write call command, if you do not write the script but b write directly to the path, bat can still run, but b After running the script, the entire batch exits. For example, we will call b.bat a script to remove the call, the script will print the value of a variable, and then assign the variable b, but will not return to a script to print the value of b again.


(To be continued)


Guess you like

Origin blog.51cto.com/181647568/2423728