Batch Script - Using the SHIFT Operator



One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation.

Example

@echo off
echo %1
echo %2
echo %3
echo %4
echo %5
echo %6
echo %7
echo %8
echo %9
echo %10

Output

If the above code is stored in a file called test.bat and the file is run as

test.bat a b c d e f g h i j

Then following will be the output.

a 
b
c
d
e
f
h
i
a0

As you can see from the above output, the final value which should be shown as ‘j’ is being shown as a0. This is because there is no parameter known as %10.

This limitation can be avoided by using the SHIFT operator. After your batch file handled its first parameter(s) it could SHIFT them (just insert a line with only the command SHIFT), resulting in %1 getting the value B, %2 getting the value C, etcetera, till %9, which now gets the value J. Continue this process until at least %9 is empty.

Let’s look at an example of how to use the SHIFT operator to overcome the limitation of command line arguments.

Example

@ECHO OFF
:Loop

IF "%1"=="" GOTO Continue
   echo %1%
SHIFT
GOTO Loop
:Continue

If the above code is stored in a file called test.bat and the file is run as

test.bat a b c d e f g h i j

Then following will be the output.

a 
b
c
d
e
f
h
i
j

Note

Some characters in the command line are ignored by batch files, depending on the DOS version, whether they are "escaped" or not, and often depending on their location in the command line −

  • Commas (",") are replaced by spaces, unless they are part of a string in doublequotes.

  • Semicolons (";") are replaced by spaces, unless they are part of a string in doublequotes.

  • "=" characters are sometimes replaced by spaces, not if they are part of a string in doublequotes.

  • The first forward slash ("/") is replaced by a space only if it immediately follows the command, without a leading space.

  • Multiple spaces are replaced by a single space, unless they are part of a string in doublequotes.

  • Tabs are replaced by a single space.

  • Leading spaces before the first command line argument are ignored.

  • Trailing spaces after the last command line argument are trimmed.

batch_script_functions.htm
Advertisements