4. Creating and viewing files

4.2. Display contents of files

Now display the contents of the file on the screen.

1. Type:
type listdir.bat <ENTER>


With the type command you can view the contents of a file.

2. Now type:
listdir <ENTER>


Congratulations! You have created your first script, a batch file. Batch files are scripts that can be used to execute commands in batch. In this case the file executed dir /AD.
Because batch files always have the file extension .bat, the computer knows that this is a batch file and will execute the commands in the file. We'll come back to this later.

3. Let's create another file. Type:
dir > list.txt <ENTER>

This command will not show the result of the dir command on the screen, but saves it to an ASCII file (text file) called list.txt. So we can use > after a command to save its results to a file instead of printing it to the screen.

4. Check the contents of the file:
type list.txt <ENTER>

You can see that the list is larger than your screen.

5. Type:
type list.txt | more <ENTER>


The result of list.txt is given to the more command which displays the results in pages as big as your window. Press   <ENTER> to see the next line. Press <SPACE BAR> to see the next page. Press <CTRL-C> to stop. You can use this last key combination to stop any command if it isn't doing what you like, it crashed or it takes too long.

6. Type:
more <ENTER>

Nothing happens, because the more command expects input from another command. So you can wait forever. In this case you can stop the execution of the more command by using <CTRL-C>.


7. Now try this:
type listdir.bat >> list.txt <ENTER>

8. Display the result:
type list.txt | more <ENTER>

9. What happened?

In summary:

  • > saves the result of a command to a new file. If the file on the right hand of > already exists, it will be overwritten.
  • >> appends the result of a command to an existing ASCII file.
  • | uses the result of the command on the left hand side in the command on the right hand side of the |. This is called a pipe.
  • Use <CTRL-C> to stop the execution of a command.
We can also use these operators to create so called lock files. These are used in scripting. The script will check if a certain file exists. If it exists, the program will wait, if it is removed, the program continues. Therefore, these files can be empty. You can create a lockfile with: type NUL > lockfile.txt <ENTER>