David Y.
—How can I write a batch script that takes arguments from the command line?
Batch scripts can access up to nine arguments from the command line using the syntax %1
to %9
. For example, the script below will print out three provided arguments, each on their own line:
@echo off echo %1 echo %2 echo %3
If we save this script as echothree.bat
, we can execute it as follows:
echothree.bat One Two Three
This will produce the following output:
One Two Three
%0
contains the name of the script and %*
contains all specified arguments – this is useful if we want to allow a variable number of arguments, or if we want to pass all of the arguments to another script or program. For example, this script would produce the command used to execute it:
@echo off echo %0 %*
For longer scripts, we can create variables containing our argument values as follows:
@echo off set name=%1 set type=%2 echo Processing %name% of %type% ...
When dealing with numeric values rather than strings, we need to pass the /A
flag to set
:
@echo off set /A a = %1 set /A b = %2 set /A sum = %a% + %b% echo %sum%
If we need to handle more than nine arguments, we can use the shift
command. This command moves all argument values back by one – %1
is moved to %0
, %2
is moved to %1
, and the previously inaccessible tenth argument is moved to %9
. We could also use this method to consume all arguments as %1
, which may be useful when creating scripts that take arguments in any order (e.g. arguments with flags like -a
and -b
).
We could use shift
to rewrite echothree.bat
as follows:
@echo off echo %1 shift echo %1 shift echo %1 shift
Note that calling shift
will not affect the value of %*
.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.