Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
xxxx / Lab1.docx
Скачиваний:
7
Добавлен:
25.02.2016
Размер:
2.14 Mб
Скачать

Using command line arguments

We can pass parameters through the command line. Parameters can be accessed in batch programs with the notation %1 to %9. There are also two other tokens that you can use:

%0 is the executable (batch program) name as specified in the command line;

%* is all parameters specified in the command line.

Batch programs can only handle parameters %0 to %9:

%0 is the program name as it was called

%1 is the first command line parameter

%2 is the second command line parameter

and so on till %9.

The batch program’s limitation to handle parameters up to %9 only can be overcome by using SHIFT. Let us assume your batch program is called with the command line parameters A B C D E F G H I J K. Now %1 equals A, %2 equals B, etcetera, until %9, which equals I. However, %10 does not equal J but A0; %10 is interpreted as %1, immediately followed by a 0. Does that mean the rest of the parameters is lost? Of course not. After your batch program handled its first parameter(s) it could SHIFT them, resulting in %1 getting the value B, %2 getting the value C, etcetera, till %9, which now gets the value J.

Example 4.

Step 1. Create a batch program name.bat as shown below.

@echo off

echo My name is %1

echo My surname is %2

Step 2. In the command prompt run the batch program with two parameters – your name and surname:

name.bat Jane Smith

For the result refer to Figure 12.

Figure 12. Using parameters

To change the position of command line parameters in a batch program use shift command.

The syntax is

shift [/n]

where /n means start at the nth argument, where n may be between zero and eight.

Given %1=the, %2=quick, %3=brown

SHIFT

will result in %1=quick, %2=brown

A second

SHIFT

will result in %1=brown

Given %1=the, %2=quick, %3=brown, %4=fox

SHIFT /2

will result in %1=the, %2=brown, %3=fox

Example 5.

Step 1. Create a batch program names.bat as shown below. Here rem command appears: it records comments (remarks) in a batch program.

@echo off

echo Filename is %0

echo My name is %1

echo My surname is %2

shift

rem The result after shift

echo.

echo After Shift

echo Filename is %0

echo My name is %1

echo My surname is %2

Step 2. In the command prompt run the batch program with two parameters – your name and surname:

names.bat Jane Smith

For the result refer to Figure 13.

Figure 13. Using shift command with 2 parameters

Step 3. Now run the batch program with three parameters as shown on Figure 14. The third parameter became the second after shift.

Figure 13. Using shift command with 3 parameters

Соседние файлы в папке xxxx