How to pass arguments in a batch file

Share

A batch script is a plain text file containing a series of commands to be run by the command-line interpreter. Although it’s not frequently used for programming or practiced, and isn’t trendy, yet its control and supremacy over Operating System environments like Windows can’t be ignored. A quick series of instructions sent into the Command Prompt may perform and carry out almost any activity or action.

Syntax:

In a batch file, you can access arguments using special variables such as %1, %2, %3, and so on. In these variables, %1 represents the first argument, %2 the second, and so forth. To illustrate, consider this example:

echo Argument no 1 is: %1
echo Argument no 2 is: %2
echo Argument no 3 is: %3

Running batch file in Windows:

To pass arguments to a batch file in Windows, move to the directory where the batch file is located. Then, you can simply include them after the batch file’s name when running it from the Command Prompt.

myscript.bat argument1 argument2 argument3
Command to pass arguments in file in Windows

In this example, %1 would contain “argument1,” %2 would contain “argument2,” and %3 would contain “argument3.”

Accessing all arguments:

To access all arguments as a single string, use %*:

echo All arguments: %*
Batch code to get all arguments

Running batch file in Linux:

Running a Windows batch file in Linux typically requires Wine for compatibility. Install Wine in your Linux OS. To execute a batch file in Linux, use the following command:

wine cmd /c "myscript.bat" arg1 arg2 arg3 2>/dev/null
Command to run on Linux terminal

This command runs the myscript.bat file using Wine while passing arg1, arg2, and arg3 as arguments. The 2>/dev/null part redirects any error messages Wine generates, ensuring a clean and silent execution.

echo Argument no 1 is: %1
echo Argument no 2 is: %2
echo Argument no 3 is: %3

You can utilize the provided Linux terminal below to practice passing parameters to a batch file myscript.bat.

Terminal 1
Terminal
Loading...

Copyright ©2024 Educative, Inc. All rights reserved