Introduction to Operating Systems Lab 1 – Command Line ...

10 downloads 2051 Views 1MB Size Report
Apr 2, 2011 ... Lab 1 – Command Line Programming. 1 Introduction: The command line interface (or command line shell) is a mainstay for system.
Bridges To Computing Brooklyn College M. Meyer, 2009

Introduction to Operating Systems Lab 1 – Command Line Programming 1 Introduction: The command line interface (or command line shell) is a mainstay for system administrators, power users and hackers as it allows them to interact rapidly with a computer without having to click through numerous graphic menus. Moreover groups of instructions to the command line interface can be assembled together into what are known as batch (or script) files. These batch files allow the automation of complex tasks, and are analogous to primitive programs. Should you ever find yourself repeating a series of basic instructions to a computer (moving and renaming files for example) you might be able to save yourself a lot of time and effort by creating a batch file program to automate that task. Today we will explore some aspects of the windows command line interface and make a simple game using a batch file. For more information on Windows command line programming, feel free to check out these online resources:  Complete List of Windows Prompt Commands  Windows Commands by Operating System  Princeton Tutorials on Using Windows Commands

1.1 Starting the command line window The command prompt is run from its own window by invoking the command interpreter that is provided by the file cmd.exe located in the Windows\System32 folder. There are two basic ways to start the command line interface:  The command prompt window can be opened by entering "cmd" (without quotes) into Start-Run box.  The command prompt window can be opened going to Start then All Programs then Accessories and then selecting Command Prompt. A black and white window (the colors can be changed) containing the command prompt will open.

http://bridges.brooklyn.cuny.edu

1

Bridges To Computing Brooklyn College M. Meyer, 2009

2 Basic Commands The command prompt is an interface to the operating system; the first thing you will need to learn is how to get around.

2.1 Finding the current directory The cd command can be used is to determine your location in the file systems. If you type cd (lowercase) into the command prompt window and hit return you should see something like the following: C:\Users\meyer>cd C:\Users\meyer C:\Users\meyer> The first line is what is called the command prompt. It ends with a > and by default shows the users location in the file structure. The result of typing in the cd command and hitting enter is displayed on the second line, and the third line is the command prompt again. It may seem silly that the cd command gave us the same information that is already in the prompt, but that is only because we have not changed the prompt.

2.2 Changing the command prompt You can change the command prompt line (hereafter called the 'prompt') to say anything you wish. Let’s do that now. Type in the following and hit return: prompt awaiting instructions: Your command prompt line should now say "awaiting instructions: " You can change it to say anything you want. It is sometimes useful to have the prompt display the time, which can be accomplished by typing the following: prompt $T To see even more options for setting the prompt type in the following and hit return: help prompt You can play with those options if you wish, but for now let's return the prompt to its original state by typing in the following and hitting return: prompt $P$F

http://bridges.brooklyn.cuny.edu

2

Bridges To Computing Brooklyn College M. Meyer, 2009

2.3 Looking Around using dir Type in the following and hit return dir The directory command (dir) will give you a listing of all the files in the current folder. You can find out more about the dir command by typing in: help dir I like to use the "wide list" format with the directory command which looks like this: dir /w

2.4 Moving around using cd When you are done exploring the dir command we need to work our way to the desktop folder (which is the folder that contains the icons on the 'desktop' that you see when working in the windows Graphic User Interface). We have already used the cd command to identify the current directory; you can also use the cd command to change directories. Type the following and hit enter: cd Desktop You should now be in the Desktop folder and you should be able to confirm this by looking at the prompt (if you are not using the standard prompt then type cd by itself as you did in section 2.1 to confirm). Let's go back to the directory we just left, which you can do by typing the following: cd .. The two dots ( .. ) tell the command to go back up one folder, and thus you should be back in the directory you started on. Let's go back to the Desktop folder but this time let's do it without typing in the full name Desktop. Instead type in the following: cd De and then hit the TAB key. What happened? Hit enter to proceed to change to the Desktop directory. For more information about the cd command use the help command we used in sections 2.3 and 2.4.

2.5 Creating a new directory You should be in the desktop folder (you can confirm this by typing cd) where we would like to create a new folder to hold the remaining files we will create in this

http://bridges.brooklyn.cuny.edu

3

Bridges To Computing Brooklyn College M. Meyer, 2009

lab. You can create a new folder (name lab1) by typing the following and hitting enter: mkdir lab1 If you look at your desktop you should now see a new folder called lab1. Use the cd command to move to the lab1 folder.

2.6 Other commands There are many other useful commands that you can use to create, move, modify and delete files and folders. In fact anything you can do using the windows GUI you can also do using the command line interface. Instructions for using the other command line interface (CLI) commands can be found online at: http://pcsupport.about.com/od/commandlinereference/tp/command-promptcommands-p1.htm A complete list of the command available to you in the CLI can also be obtained by typing in the following command (and hitting return): help Before we go, try one last command, and make a note of what it does:

cls

3 Starting programs: Windows keeps track of the names of the programs that are installed on it, and can search for and try and load programs by name. In the next section we are going to want to create a batchfile using the program called Notepad (which comes built-in to Windows). We can start the Notepad program from the CLI simply by typing the name of the program (Notepad) and then hitting enter. However, it is worth noting that many programs can also be given "input parameters" which are additional instructions to use as the program starts up. For example we can start the Notepad program AND get it to create and name a file called mygame.bat for us by typing in the following command and hitting enter: notepad mygame.bat You should now see something like the following (note: you may get an error message saying that the file mygame.bat cannot be found, and you should tell windows to create that file):

http://bridges.brooklyn.cuny.edu

4

Bridges To Computing Brooklyn College M. Meyer, 2009

4 Creating a batch file A batch file (or script file) is simply a text file which contains a list of commands designed to be run by a CLI. We are going to create a batch file today that will act as a very simple game. In the process of creating this game we will see that the windows command line environment is effectively a programming language environment as we have the ability to create variables and we can access the SEQUENCE, SELECTION and REPETITION operations necessary to support the Imperative paradigm.

4.1 Planning the game You should NEVER coding a game (or any other large programming project) without first planning out the flow of the game and accounting for any special resources that the game will require. We would like to create a simple number game, where the computer picks a number at random, and the player tries to guess that number using a limited number of guesses. After the computer has picked a random number the player will get 6 guesses. After the player makes a guess, if it is incorrect, the computer will tell the player if the guess was too high, or too low. If the player correctly guesses the number they will win, but if after 6 guesses they fail to correctly guess the number, then the player will lose. Take a moment and thing about the program you are going to create. Try and write down a pseudo-code program below, making sure to clearly identify the places where SELECTION (making a choice in the program) and REPETITION (repeating sections of code) will come into play: START

END

http://bridges.brooklyn.cuny.edu

5

Bridges To Computing Brooklyn College M. Meyer, 2009

4.2

Creating the game

4.2.1 Batch File Flow (Sequence) A bath file is a sequence of commands and in general that sequence (the order in which instructions will be read) is left to right and then top down LRTD. However there are exceptions to this general rule. We have the ability to use loops (repetition – repeating sections of code) in batch files and we can also use labels to alter the flow of the program.

4.2.2 Comments Comments are statements (bits of code) that are ignored by the computer. You should ALWAYS comment the code you write, in order to help other programmers understand what you have written. In batch files we can create comments by using the REM command. With your batch file open, add the following line to the top of the page:

The ***** sections that appear at the beginning and end of the line are not necessary, only the command REM is necessary. However, I like to add ***** sections to comments to help the comments stand out from the rest of the batch file. We will continue to add comments throughout our batch file. Save your batch file at this point and then go back to your CLI (command line interface). If you type in the name of your batch file, followed by enter, you should see the following (assuming you are in the correct folder):

What happened! Although our REM command is ignored by the computer, it is still displayed. And that is because by default all lines of a batch file will be "echoed" to the CLI window. Sometimes this is desirable, but in our case, it is not.

http://bridges.brooklyn.cuny.edu

6

Bridges To Computing Brooklyn College M. Meyer, 2009

4.2.3 Echo Go back to the CLI window and type in the following: echo Hello What happened when you hit enter? The echo command is used to send information to the CLI window; in our batch files we will use it as a command to have information printed for the user to see. In a batch file, by default, echo is turned on, which means that every single line that we put in our batch file will be shown in the output window. We don't want that, we only want the window to show specific information. Therefore, we need to change our program is turn echo off, and this should be the first line in our program. We can do this by adding the following command to our program: @echo off Your batch file should now look like this:

Run your program again, and see what happens.

4.2.4 Labels We are going to want to repeat parts of our program. As an example we are going to want to ask the user for a guess up to 6 times. We can return to sections of code in two ways, by using loops and by using goto statements. NOTE: We normally avoid using goto statements in high-level programming languages, but we will use goto statements today, in our batch file, because it is a very simple file. A goto to statement allows you to change the flow of a program by having the computer skip to another section of the program. You must label a section of a program if you would like to goto (literally "go to") that section. Let's add a comment and a label to the top of our program. You already know how to make a comment, and you make a label by using a colon. Make the start of your program look like this:

http://bridges.brooklyn.cuny.edu

7

Bridges To Computing Brooklyn College M. Meyer, 2009

In the file above we have added a new comment which declares the start of the program, and we have created a label called startOfProgram as well. In the future, we will be able to make the computer return to this part of the file by using the statement: goto startOfProgram Do not add such a goto statement to your batch file at this time.

4.2.5 Variables A variable is a name and value pair. For example: x=4 says that there exists something name x which has the value of 4. We are going to need 3 variables for our program.  secretNumber -> the number the computer picked  guess -> the number that the player is using as a guess  counter -> the number of guesses the player has made You can create a variable using the set command. Add the following lines to your program: set counter=0 set secretNumber=0 set guess=0 What did you just do? What are the names and values of each of your variables?

4.2.6 Sending output to the CLI window The game will need to ask the player questions and tell the player if their answer is correct or wrong. In short our batch file needs to be able to send information to the screen. We have turned echo off so be default none of the lines in our file will appear in the CLI window when the batch file is run. We can however deliberately send information to the CLI window by using the echo command…. again.

http://bridges.brooklyn.cuny.edu

8

Bridges To Computing Brooklyn College M. Meyer, 2009

Make your batch file look like this:

Now run your program (batch file) by going to the CLI window and typing mygame.bat What happened? You should have seen something like this:

Our program first turns of echoing, so that the actual commands we have in our batch file are not printed to the screen. We then have two comments and a label, all of which have no output. Then we create our 3 variables using the set command. What were their names and values again? Then we have our first echo command. What is printed to the screen is the number 0. Why? The name of our first variable is counter but its value is 0. When we used the echo command we surrounded counter with % signs. Theses % signs tell the computer that we want to echo the value of the variable and not the name. After echoing our 3 variable values we also echo 5 lines which create a "Title" for our game. Notice the last line which has an echo followed by a period. That line creates an

http://bridges.brooklyn.cuny.edu

9

Bridges To Computing Brooklyn College M. Meyer, 2009

empty echo line. The period literally says echo EXACTLY what is written, and what is written is an empty line. If we use the keyword echo and follow it with an empty line, we will get the value of echo (false) which is not what we want. We are going to need to echo variable values in our program and we will do that using the % sign (formally the % is then known as an "escape key" or "escape sequence" as it specifies a modifier on what should be displayed). But for now remove the 3 echo lines that print out 0's (the 3 echo variable lines).

4.2.7 Special Functions Our secret number is currently 0. That won't do. What we need is for our secret number to be a random value between 0 and 100. The windows CLI has a special function called "random" which can generate random numbers, unfortunately it will generate a random number between 0 and 4,294,967,295 ( which equals to 232 ) and we don't need numbers that large. So what we can do is use the special function modulus to take an random numbers that are too large and reduce them so that they are between 0 and 100. Add the following lines of code to the bottom of your program: :playAgain set /a secretNumber = %random% %% 101 set counter=0 echo I am thinking of a number between 0 and 100. echo Can you guess the number in 6 tries or less? echo. It should be clear to you that the first line is simply creating a new label (named playAgain). The 3rd line is setting the counter variable value to 0 and the last 3 lines are simply printing two sentences and an empty line to the screen. The second line may be a bit confusing; it is enough for now to know that it is setting the secretNumber variable to a random number between 0 and 100 (the /a following set, means set the value equal to an arithmetic equation, ask your instructor for help in understanding the rest of the line.)

4.2.8 Getting input from the user In the last section we set our secretNumber. Now we need to get a guess value from the user. In the last section we used /a (a command line operator) in combination with the set command to make a variable equal to an arithmetic equation. In this section we will use the /p command line operator to set a value equal to the result of input from a prompt. Add the following lines to your program: :guess set /p guess="Enter your number (0-100) : "

http://bridges.brooklyn.cuny.edu

10

Bridges To Computing Brooklyn College M. Meyer, 2009

What do you think those lines do? Run your program. What happened?

4.2.9 Selection In the last two sections we created a random value for the variable secretNumber and we asked the user to submit a value and assigned that value to the variable guess. Now we want to compare the secretNumber and guess variables to see if they are the same. If they are the same then the player has won (and we should tell them so). Add the following lines to your program: if %guess%==%secretNumber% goto :win goto :guess :win echo Congratulation, you win. Thanks for playing! What does each of the lines above do? What would happen if we didn't put those % symbols around the variable names? Now run your program. What happened?

NOTE: To stop a running batch program, hold down the CTRL and C buttons at the same time. 4.2.10

Repetition (counter controlled)

It may be clear to you at this point, that the lines we added in the last section implemented repetition. If the users guess is not equal to the secret number then they are sent back to the section of code that has the label guess, and are asked to enter another number again. The program you have now will loop until the player guess the correct number (or you stop it by hitting ctrl+c). Let's change that so that the player only gets 6 guesses. We already have a variable called counter. What we need to do is add one to the counter variable after each bad guess, and after 6 bad guesses send the player to a "you lose" labeled section of code. Make the bottom of your program look like this (new lines are added in bold): if %guess%==%secretNumber% goto :win set /a counter=%counter%+1 if %counter%==6 goto :lose goto :guess :lose echo Sorry, you lose. :win echo Congratulation, you win. Thanks for playing!

http://bridges.brooklyn.cuny.edu

11

Bridges To Computing Brooklyn College M. Meyer, 2009

What does each of the NEW lines above do? What would happen if we didn't put those % symbols around the variable names? Now run your program. What happened?

4.2.11

Finishing up

We're almost done. You should have noticed two things when you ran your program: (1) It's very hard to win and (2) After you get the "Sorry, you lose" message then you also get the "Congratulations, you win message". Let's tackle the second problem first. Remember that the SEQUENCE of a batch file is LRTD, and so after we leap to the lose label, the program continues processing the batch statements that follow, including our "you win" statement. What we need to do is have the program leap to the end of the program after printing you lose. Can you see how to do that? CHALLENGE 1: Fix your program so that only the one correct message, you win or you lose is displayed when a player wins or loses. Hint: You will need to put a label at the end of the document. Now let's look at the second problem. The game is hard because you aren't told whether or not your guesses are good or bad. CHALLENGE 2: Fix your program so that if a players guesses wrongly, they are immediately told whether their guess was too high or too low, before they are asked to guess again. Hint: Use the operators from the table on the right. ( if %guess% GTR %secretNumber% echo … ) CHALLENGE 2: Right now the program automatically ends if the player guesses correctly, of if the player runs out of guesses. Modify the program so that the player can "play again" if the wish. Hint: Create a variable called "playAgain". Use the set /p command to ask the player to enter y or n.

http://bridges.brooklyn.cuny.edu

Table I. Comparison operators in"If' statements Operator

Meaning

EQU

equal to

NEQ

not equal to

LSS

less than

LEQ

less than or equal to

GTR

greater than

GEQ

greater than or equal to

12