Learn Windows Command Prompt by example: Beginners introduction to Cmd

There are times when you need to run a command-line application. This article shows how, using an example. We will convert a PNG file to WebP using Google’s Libwebp application. As we work through the example, we will learn many important Cmd commands, including some advanced ones. In the end, we will see how to convert multiple images with a single command.

Download and extract the application

If you like to follow along with the guide, download the application from this page https://developers.google.com/speed/webp/download. Click on the Download for Windows link on that page. Extract the contents of the zip file. If you don’t have a compression program like Winzip or 7zip installed, you can use the zip support built into Windows. Right-click of the zip file and choose extract all from the context menu. If another program is already associated with the zip file type, the built-in Windows option will not be available.

Open the Cmd Terminal

  1. Open the Start Menu
  2. Type cmd
  3. Press Enter

Starting the command prompt from the Start Menu

Using the Cmd Terminal

The black window that you see is the Terminal window. You type a command in the Terminal and press Enter. Cmd will try to interpret your command. If you have typed a valid command, it will run that command. 

Commands in Cmd are typically not case-sensitive. For the most part, you can use any case you like; title case, all caps, lowercase are all valid.

The command which we have to run

Libwebp’s documentation gives this example for the most basic conversion command:-

 cwebp input.png -q 80 -o output.webp

We will be sticking to basics here and won’t be looking at any of the advanced options of Libwebp. It is useful to take a close look at the conversion command since its structure is similar to commands used by many other command-line applications.

cwebp conversion command break down

  • cwebp is the name of the executable we need to run to create a WebP file. Remember that we extracted the contents of the Libwebp zip file, cwebp.exe can be found inside the bin folder. When running a command-line application typing the .exe at the end is optional. So you can type cwebp instead of cwebp.exe.
  • Input.png is a sample name for the input file. We must use our real input file name here. So if we are converting cat.png, type cat.png instead of input.png.
  • The -q is something called a command-line option or a command-line switch. In cwebp -q represents quality, it tells cwebp that the value which follows -q, 80 in this case, is the quality that we want.
  • The -o option represents the output file name. Specify the name of the output file name you want, immediately following the -o.

Folder vs Directory

In Windows, you may be more familiar with the term folder. You could think of a folder and a directory as the same, even though there is a small difference. A directory is a location in the file system. All directories are folders, but not all folders are directories. Windows has a few special folders like the Control Panel which are not directories. Cmd does not support these special folders and uses the term directory to refer to your normal folders. Since this article is mostly about Cmd, I will also be using the term directory instead of folder.

The problem of paths

Earlier, we saw the command that we need to run. However, if you copy and paste it into the terminal, you will most likely see the following error message.

Error message about unrecognized command

The problem here is that Cmd cannot find the cwebp executable, it will not search the whole computer for a file named cwebp. There is another problem lurking in there as well, even if Cmd manages to find cwebp, cwebp will not be able to find input.png.

Solution 1: A GUI based solution

Since Cmd is having trouble finding cwebp, we could tell Cmd exactly where cwebp is located.  This means specifying the full path to cwebp. Similarly, we can specify the full path to input.png to help out cwebp.

Finding the path to a file

Open the folder containing cwebp.exe and shift + right-click on the cwebp.exe file. You will see a context menu like the one shown below, choose the option copy as path.

Windows extended context menu

Please remember that this menu is the extended menu which is shown only if you do shift + right-click. If you fail to press shift you will see only the normal menu which does not contain the Copy as path option. The path to our input image can also be found using the same method.

Specifying the path to the output file

Let us specify the path to the output file as well, even though the command will work without it. If we don’t specify the full path, the output file will be created in what is called the current working directory. We will discuss the concept of current working directory later in the article. 

Since the output file does not exist as yet, we first need to figure out the path to the output directory.

  • Shift + right-click on the directory where you want the new file to be saved.
  • Choose the Copy as path option from the context menu.
  • Add a \output.webp just before the ending quote. For example, I got “D:\temp” as the directory path, so I used “D:\temp\output.webp” as the output path.

Command using full paths

The command using full paths would look something like this:-

"D:\Prog\libwebp\bin\cwebp.exe" "C:\Users\admin\Pictures\input.png" -q 80 -o "D:\temp\output.webp"

Your paths will most likely be different from mine, but that is fine. Notice the double quotes around the path, those are required if your path contains a space. The Copy as path option automatically puts quotes around all paths.

Output of cwebp command

Copy as path option is very useful when working with the command line. However, to become efficient on the command line, we must minimize its use. We will discuss how, in the following sections.

Understanding Paths

As we have seen, paths in Windows has the form D:\Prog\libwebp\bin\cwebp.exe. Here is a break down of this path:-

  • D: is the drive letter. Each disk partition in Windows has a drive letter. They are usually named C, D, E, F, etc.
  • The backslashes (\) represent something called a path separator. They are used to separate the various components of a path.
  • Prog is a directory inside D:
  • libwebp is a directory inside D:\Prog
  • bin is a directory inside D:\Prog\libwebp
  • cwebp.exe is a file inside D:\Prog\libwebp\bin

A path can also point to a directory instead of a file. The path to the bin directory from the previous example would be: D:\Prog\libwebp\bin

Add the executable location to the Path variable

Typing the full path to an executable is fine as long as you are not planning to use it again. But if you plan to use it often, its path must be added to the Path variable.

What is the Path variable?

Path is a special environment variable of Windows. The value of the Path variable is a semicolon-separated string of paths, all pointing to directories. If you find terms like environment variables, variable values, etc confusing, don’t worry. All you need to understand is that, in effect, the Path variable is just a list of paths to directories.

As mentioned earlier, if Cmd fails to find an executable, it will not search the whole computer for it. However, it does search inside all the directories that have been added to the Path. So if we add the directory containing cwebp.exe to the Path, we no longer need to type the full path to the file. Cmd does not search subdirectories in order to keep the searches fast. So adding the whole Libwebp directory does not help. We need to add the bin directory where cwebp.exe is located.

  • If the command line application came with an installer, in all likelihood the installer would have automatically added the required paths. For example installers for Python, Java etc automatically sets the required paths.
  • The Path variable is for executables only. Cmd looks for executables in the Path. However, the internal commands or executables run by Cmd do not look for files that it can’t find in the Path. So in our example, there is no point in adding our picture directory to the Path variable, since cwebp.exe will not look for them there.
  • Command-line applications often consist of a single executable without any installer. It is probably better to choose a single dedicated directory as the location for all such applications. Then add that directory to the Path. This way we can avoid having to modify the Path variable every time we need a new command-line application. Just copy the executable to our chosen directory and it will become available directly in the command line. However, Libwebp consists of multiple files and directories, so this method is not suitable for our example.

Solution 2:-

Now we need to add the bin directory to the Path variable. Please read the article add folder to system path in Windows 10 to see how. Once you are done, you can use the following conversion command.

cwebp "C:\Users\admin\Pictures\input.png" -q 80 -o "D:\temp\output.webp"

Understanding the current working directory

In order to reduce the tediousness of having the type too many paths, the command-line has a concept called the current working directory. When the command-line terminal opens it already has a current working directory set. In Windows, the default working directory might be different depending on how you start Cmd. It is possible to change the working directory later.

How does it help?

If we ask Cmd to run an external command, the current working directory is the first place it looks. External command means a command which is not part of the Operating System but provided by an external executable, like cwebp in our case. Similarly, both external and internal commands will look for files/directories in the current working directory. So if a command requires a path and we don’t specify the full path, it is assumed that the file or directory in question is in the current working directory.

How to find which is the current working directory?

The path to the current working directory will be shown to the left of the blinking cursor.

Command Prompt

In the above picture, the current working directory is C:\Users\admin. You can also view the current working directory by typing the command CD.

Output of CD command

How to change the current working directory?

Use the CD command to change directory. The format is CD, followed by a directory path.

    • Copy the path to the picture folder using the Copy as path method.
    • Type the command: CD <the path you copied> Example:CD "C:\Users\admin\Pictures"
    • Press Enter

Change Directory command and its result

As you can see in the above picture, the command prompt changed from C:\Users\admin\ to C:\Users\admin\Pictures. This means that C:\Users\admin\Pictures is now our current directory.

Relative paths

It happens that, in our example, the old path and the new path are quite close to each other. In fact, the new working directory is a child of the old working directory. In situations like these, there is an easier way to change the working directory. But first, let us see how to go back to where we were before. In Cmd .. represents the parent directory. So we can use the command CD .. to go to the parent directory.

Go to parent directory

Since Pictures directory is a child of the admin directory, we can make use of something called relative paths. Relative paths are paths relative to the current working directory. Instead of using the whole path, we can just use cd pictures.

Relative paths example

Let us say, you are in the admin folder and want to go to a child directory of Pictures. You don’t need two cd commands, you can do this: cd Pictures\Screenshots

Relative paths example

Let us try something a bit fancier; consider the directory structure shown below.

Directory Structure Sample

 

Let us say, our current directory is Pictures and we want to go to Videos with a single command. Remember that .. stands for the parent directory, we can use .. in a path as well. In this case, we can use the command cd ..\Videos

Relative paths example

  • The .. takes you to the parent directory of the current directory.
  • The \Videos takes you from the parent directory to Videos.

Open the Cmd Terminal with a different working directory

If the directory of interest is already open in Windows Explorer, you may want to open Cmd with this directory as the working directory. Please read this short article to see how.

Tab auto-completion

The Cmd terminal supports tab auto-completion for files and directories. This means that you don’t have to type the full name of files or directories. Type the first few characters of the name and hit the tab key; Cmd will automatically fill in the rest of the name. 

Let us say, we are in the admin directory from the above example and want to use auto-complete for the Pictures directory. Do the following: Type p and press tab. Cmd will find all files and directories in the admin directory which starts with p and automatically complete the one which comes first alphabetically. What if there is more than one file/directory which starts with p? Then you will have to hit tab again to cycle through all the contenders. We can reduce the number of tab presses required by filling in more characters from the name before pressing the tab key. For example, we can type Pi or Pic before pressing the tab.

Tab completion is not supported for internal commands or for executables that we place in the Path. To take advantage of tab completion, you must either use full paths or the file or directory in question must be inside the current working directory. Tab auto-completion works differently in the PowerShell terminal, some of the third-party Cmd terminals, most Linux terminals, etc. 

Solution 3:

Now we are ready to execute the simplest version of the conversion command. CD into the directory containing the picture and type the following command:-

cwebp input.png -q 80 -o output.webp

This is the same command shown in the official documentation.

Some important commands

If you plan to be spending a lot of time on the command line, you need to learn more commands. Here are some important commands to get you started. Please note that this is only a brief description of the commands.

DIR

DIR is probably the most useful command after CD. It displays the contents of a directory. DIR command without any parameters displays the contents of the current working directory.

Basic command

Output of dir command

If you want to see the contents of a different directory, supply the path to the directory as a parameter. Both absolute paths and relative paths are supported.

Examples:-

dir Pictures
dir "C:\Users\admin\Pictures"

List only files

dir /a-d-I

List only directories

dir /ad

Recursive listing 

The DIR command on its own lists only the top-level contents of a directory, it does not recurse subdirectories. With the /s option we can list the entire contents of a directory.

dir /s

DIR has the option to search for a file. Instead of specifying a directory to list, you can specify a file to search for. This feature becomes extremely useful when combined with the /s option.

dir compile_commands.json /s

This command will search the entire working directory recursively for files named compile_commands.json. More flexible searches are possible with the help of something called wildcards. Let us say, we want to find all PNG files inside the current directory.

dir *.png /s

The asterisk (*) character is a wildcard, it can match zero or more occurrences of any character. So *.png will match any filename which ends with .png.

To find all PNG files with name starting with “scan”, use the following command.

dir scan*.png /s

Sorting

Use the /o option to sort (order) the list. Combine the /o with one or more of the following modifiers to get the desired order.

n Sort by name
e sort by extension
d sort by date; oldest first order
s sort by file size; smallest first order
g Show directories first

To order files by date:

dir /od

It is also possible to reverse the default order. For this, put a – before the modifier. Newest file first:

dir /o-d

It is also possible to combine modifiers. To sort first by extension, then by date:

dir /oed

Make Directory

You can create a new directory using the MKDIR command. The form of the command is mkdir <path to directory>.

mkdir test_dir

Creates a directory named test_dir in the current directory.

Copy Files

Use the COPY command to copy files. The format is copy source destination.

copy input.png Screenshots\test

If you want to rename the file along with copying, you can use the full path to the new file.

copy input.png Screenshots\test\new_input.png

You can use wildcards to copy multiple files.

copy *.png Screenshots\test

copies all png files to Screenshots\test

Copy Directories

The COPY command does not support copying directories. Use robocopy to copy directories.

robocopy Test Screenshots

This command copies the top-level contents of Test to Screenshots, it does not copy subdirectories. Also, the directory is not copied only its contents are. To copy a directory and its top-level contents use the following command.

robocopy Test Screenshots\Test

Technically the above command does not copy the directory along with its contents. It creates a new directory with the name you specify and puts the contents of the source directory in it.

Use the /s switch to copy subdirectories as well.

robocopy Test Screenshots\Test /s

This still does not copy empty subdirectories, to copy absolutely everything use the /e switch.

robocopy Test Screenshots\Test /e

Robocopy command can be used for copying files as well.

Move Files and directories

The MOVE command can be used to move both files and directories.

move input.png C:\Users\admin\Pictures\Screenshots\test

To rename the file along with moving, use the full path to the new file.

move input.png Screenshots\test\new_input.png

You can use wildcards to move multiple files.

move *.png Screenshots\test

moves all png files to Screenshots\test.

Using the MOVE command to move a directory.

move test Screenshots

Rename files and directories

Use the RENAME command to rename files and directories.

rename Screenshots\screen1.png Screenshots\screen_renamed.png

Most Cmd commands support wildcards. However, you need to be careful while using them.

Batch Processing

With command-line applications, it does not matter whether the application support batch processing or not. The command-line itself has features that allow any command to run in batch mode. 

The FOR command can be used for this purpose. The FOR command has multiple features, but its main feature and the one we are interested in is its ability to run a command for each file in a set of files.

The format of the FOR command is:-

FOR %variable IN (set) DO command [command-parameters]

Breakdown of the FOR command

  • FOR, IN and DO are keywords.
  • The set tells the FOR command which files/directories we want to process. We must replace the word “set”, with a specification for the file set. There are multiple ways to do this, the easiest is to use wildcards. For example, *.jpg means all JPEG files in the current directory. We will look at some of the advanced methods later.
  • %variable is the name of a memory location. It is up to us to choose a name, but there are a few rules. The name must have only one letter and we must put a % before it. For example %a, %A, %i etc. If you are writing a batch file instead of typing commands in the command line, the name must start with %%; like %%a, %%A, %%i, etc. Variable names are case sensitive.
  • The command is what we want to execute repeatedly for each file in the set. For the command to be useful, the %variable must be integrated into it. I will explain how to do this in the next section.

How does it work?

Let us look at an actual example:-

for %i in (*.png) do echo %i

This command prints the names of all PNG files in the current directory. Let us see how this works.

  1. From our set specification: *.png; FOR creates a list with the names of all PNG files.
  2. It takes the first item from the list puts it in the variable %i.
  3. It then calls our command. The command is echo %i, which prints whatever is stored in the variable %i to the screen. Since FOR just placed the name of the first file in %i, that is printed.
  4. Steps 2 and 3 are repeated, only this time, the name of the next file is processed. This continues until all the files in the list are processed.

Batch Conversion using Libwebp

Let us batch convert images to WebP using the FOR command. Remember that the cwebp command had the form:-

cwebp input.png -q 80 -o output.webp

In this command, there are two parameters which have to change each time the command is run, the input file and the output file. To integrate this command into FOR, we need to figure out how to specify the input file and output file using our %variable.

The input file name is easy, FOR gives you the input file name before it runs our command. We can do the same thing we did with the ECHO command. 

The output file requires some work. We need a different output file name each time the command is run. A common solution is to use the same name as the input file but with a different extension. So if the input file is cat.png, we will use cat.webp as the output file name. For this, we need to learn some of the additional options of the FOR command.

Extracting additional information from the %variable

As we have seen the FOR command places the filename in %variable, before calling the command. It is possible to extract more information regarding the file using the %variable. For example, if your variable name is %i and you use %~ni in the command, you will get the name of the file without its extension. Here is ~n is called a modifier. Modifiers must be placed between the % sign and the variable name.

for %i in (*.png) do echo %~ni

This command prints the names of all PNG files in the current directory without extensions.

for %i in (*.png) do echo %~fi

This command prints the full path to all the PNG files in the current directory using the ~f modifier.

We will discuss a few more variable modifiers later in the article.

Spaces in paths

As mentioned before if your path contains spaces it must be put in quotes. Now that we are using paths stored in a variable, let us see how to achieve this. It is quite easy in CMD, you can just put quotes around the variable name so %i becomes “%i” and %~ni becomes “%~ni”.

Batch Conversion Command

Now we are ready to write the batch conversion command.

for %i in (*.png) do cwebp "%i" -q 80 -o "%~ni.webp"

We can also use multiple wildcards like so:-

for %i in (*.jpg *.png) do cwebp "%i" -q 80 -o "%~ni.webp"

This converts both JPEG files and PNG files in one go.

Another way to specify a set in FOR command

In the previous section, we used wildcards to specify sets of files that we want to process. One problem with this method is that it ignores subdirectories. There are multiple ways to specify sets, let us look at a more advanced method.

FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

There is an extra /F after the FOR. Instead of wildcards, you can use any command which returns a list of things. The DIR command which returns a list of files and directories is a top contender here. When using the DIR command the /B switch is usually needed to get the so-called bare format. The /B switch can be combined with any of the other switches of the DIR command. For example, the /S switch can be used to recurse subdirectories.

Delimiters

The /F version of the FOR command allows you to extract tokens from within each line of output. For our example, we don’t need such advanced functionality since DIR /b output a single piece of data, the path to a file, per line. But if the command we use produces multiple pieces of data per line, delimited by commas, spaces, tabs, semicolons, etc, we can extract each piece of data by specifying which delimiter to use.

Extracting tokens using delimiters is beyond the scope of this article. So why bother mentioning them? It is because delimiters will bother us if our path contains spaces. FOR /F considers spaces and tabs as the default delimiter. So if our path contains spaces, only the part before the first space gets stored in the variable. To get around this problem we have to set the delimiter to nothing.

FOR /F "delims=" %i IN ('DIR *.png /B /S') DO echo %i

The /S switch outputs full paths instead of just file names. This is convenient since we are processing subdirectories now, so file names are not enough. As earlier, specifying the input to cwebp is easy, but the output has become even more challenging. It is not enough to get the input file name without extension and tag a .webp at the end, we need a full path. For this, we need to learn more variable modifiers available in FOR.

Variable modifiers for the FOR command

Modifier Expansion
%~dI Expands %I to drive letter only
%~pI Expands %I to a path only
%~nI Expands %I to filename only

Assumes that the variable name is %I. For a full list of all variable expansions available in FOR, please use the help command: FOR /?. It is possible to combine the modifiers; so if we write %~dpnI. we get the drive name followed by the path and the file name without extension. This is exactly what we want for our cwebp output.

FOR /F "delims=" %i IN ('Dir *.png /b /s') DO cwebp "%i" -q 80 -o "%~dpni.webp"

Leave a Comment

Your email address will not be published. Required fields are marked *