Operating systems - Command Line Interface (CMD)

Recommended reading:
Stanek, William R 2004. Microsoft Windows
Command-Line Administrator's Pocket Consultant. Microsoft Press.
[Stanek, William R 2005. Microsoft Windows parancssor.
A rendszergazda zsebkönyve. Bicske: Szak K.]
2nd Edition: Microsoft Press, 2008.

command line interface (desktops, laptops)

We can use a script language in MS DOS batch (.bat) files. A batch file contains a set of DOS commands that can be executed sequentially by the OS in a command prompt window (CMD.EXE). The simplest way to create batch files is to use the Notepad.

The syntax of the script language can be described in the BNF (Backus-Naur Form) metalanguage or its extended form. It uses the following symbols:

Batch files behaves like they were DOS commands. We can run batch files or issue DOS commands separately in a command prompt (CMD) window. In the CMD window the previously issued commands can always be recalled and edited by pressing the up (↑) and down (↓) arrows in the keyboard. Pressing the 'Esc' key erases the command line.

The operation of the DOS commands can be modified by various switches which follow the commands after a slash (/) character. The DOS commands contain a built-in help which can be be activated by using the /? switch (e.g. dir /?; note that 'help dir' can also be used). The 'help >help.txt' command can be especially useful because it lists the available internal DOS commands (in this case redirected into the help.txt file).



DOS and OS commands I.

Basic DOS and OS commands:



Redirection of the standard input and output

The standard input (con, 0), the standard output (con, 1), and the standard error text output (2) can be redirected by the following operators:

Note that the 'nul' output will hide either the standard output or the standard error output (e.g. the command 'dir xxx.abc 2>nul' hides the 'File not found.' error message if the file 'xxx.abc' does not exist)

further reading:
SS64: Command redirection, Pipes etc.


DOS and OS commands II.

DOS and OS commands to display or modify system information:



DOS and OS commands III.

Other DOS or OS commands:



DOS and OS commands IV.

Various commands that can be used primarily in batch files


I. handling variables


II. control structures

Always be careful when you modify the value of variables within the 'if' or 'for' blocks. The modified values are hidden within the block and they become visible only outside the block. This "delayed" evaluation mechanism should always be taken into consideration.
further reading:
Wikipedia: cmd.exe
Wikipedia: List of DOS commands
Tutorialspoint: Batch Script - Commands
SS64: An A-Z Index of Windows CMD Commands


Applications of the 'if' command in batch files

examine the first command line argument (firstpar.txt)

@echo off
cls

echo --- the previous value of 's' is s=%s% ---
echo:

if "%1"=="" (
 echo missing command line parameter ^('%1'^)
 set s=null
 ) else (
 echo first command line parameter: %1

 if NOT EXIST "%1" (
  echo the file '%1' does not exist
  set s=null
  ) else (
  set /A s=%~z1
  echo the size of '%1' in the 'if' block is s=%s% 
  ) 

 )

echo:
echo --- the real size of '%1' is s=%s% ---

examine the default path and add new paths (exampath.txt)

@echo off
IF EXIST temp.txt (
 del temp.txt
 )

set x=c:\temp\gcc\bin;
set x=c:\temp\jdk_22\bin;%x%
set x=c:\Windows\Microsoft.NET\Framework64\v4.0.30319;%x%
echo %x%

PATH | find "gcc" >temp.txt

call :sizeof temp.txt

IF %size% LSS 10 (
 set PATH=%x%;%PATH%
 )

path
del temp.txt
goto :eof

:sizeof
set size=%~z1
echo %size%
exit /b

Note that if the current path contains a special character (e.g. a space, as in 'Program Files') then the %PATH% reference will cause an error message.



Applications of the 'for' command in batch files I.

display the number of command line arguments (args.txt)

@echo off
set /A a=0
for %%i in (%*) do ( 
 echo %%i
 set /A a+=1
 )
echo Number of arguments: %a%

Although we have only nine default variables for the command line arguments (i.e. %1, %2, ..., %9) the args.bat batch program will list all the arguments.


another version of displaying the command line arguments (args1.txt)

@echo off
set /A a=0
:cont
if "%1"=="" goto :disp 
 set /A a+=1
 if %a% LEQ 9 (
  echo %%%a%=%1
  ) else (
  echo ^<%%%a%^>=%1
  )
 shift
 goto :cont
 )

:disp
echo Number of arguments: %a%

display the name of the files in the current directory (fnames.txt)

@echo off
for %%f in (*) do (
 echo %%f
 )

display the name and path of the directories (or folders) located in the C:\temp directory (dnames.txt)

@echo off
for /R C:\temp /D %%n in (*) do (
 echo %%n
 )

Note that the recursive 'for' command without the /D switch
    for /R C:\temp %n in (.) do echo %n
has almost the same effect (because '.' refers to itself in each directory).


display the name of all files that can be found in the directory tree starting from the current directory (tnames.txt)

@echo off
set cp=%cd%
set /A i=0
for %%f in (*) do (
 echo %%f
 set /A i+=1
 )
for /R /D %%n in (*) do (
 cd %%n
 for %%f in (*) do (
  echo %%f
  set /A i+=1
  )
 )
echo %i% file(s) listed
cd %cp%

display the first three words of each line of a given text file (token.txt)

@echo off
for /F "tokens=1-3* delims=,; " %%a in (%1) do (
 echo %%a
 echo %%b
 echo %%c
 echo ...%%d 
 )


Applications of the 'for' command in batch files II.

List the natural numbers from 1 to a specified number given by the first command line argument (numbers.txt).

@echo off
if "%1"=="" goto error_1

set /a n=%1 

if %n% GEQ 1 (
 goto :cont
 ) else (
 goto :error_2
 )

:cont
for /l %%i in (1,1,%n%) do (
 echo %%i
 )  

goto :eof

:error_1
echo missing argument
goto :eof

:error_2
echo invalid or not a number (NaN) error

Now list 'n' elements of the Fibonacci sequence (fibonacci.txt).

@echo off
if "%1"=="" goto error_1

set /a n=%1 

if %n% GEQ 1 (
 goto :cont
 ) else (
 goto :error_2
 )

:cont
set /a s1=0
echo %s1%

set /a s2=1

for /l %%i in (2,1,%n%) do ( call :subroutine )
rem be careful with assignment sentences in the loop :-(

goto :eof

:error_1
echo missing argument
goto :eof

:error_2
echo invalid or not a number (NaN) error
goto :eof

:subroutine
echo %s2%
set /a t1=%s1% 
set /a t2=%s2%
set /a s2=%t1%+%t2% 
set /a s1=%t2% 
exit /b

The assignment sentences within the loop are executed only after the 'for' statement has been finished. Therefore the 'echo' commands can display the previously assigned values of the variables (i.e. their modified values cannot be temporarily accessed). Run this batch file and analyse the problem (errpow.txt):

@echo off
set /A %a=1
set /A %n=0

for /L %%x in (1,1,5) do ( 
 echo 2 raised to %n% equals %a%
 set /A n=%%x
 set /A a*=2
 )

echo -----------------------
echo 2 raised to %n% equals %a%

Using the 'call' command inside the 'for' loop, we could modify the above batch program to display the powers of 2 correctly (errpow1.txt):

@echo off
set /A %a=1
set /A %n=0

for /L %%x in (1,1,5) do ( 
 call :pow2 %%x
 )

echo -----------------------
echo 2 raised to %n% equals %a%
goto :eof

:pow2
echo 2 raised to %n% equals %a%
set /A n=%1
set /A a*=2
exit /b
further reading:
Wikipedia: Fibonacci sequence


Applications of the command line interface I. – Say 'Hello'

(1) First, as a short reminder, let us display "Hello, World!" using a batch file (hellob.txt):

@echo off
echo Hello, World!

We can give a name as a command line argument as well (helloa.txt):

@echo off
set name=Anonymous
if "%1" NEQ "" (
 set name=%1
 )
echo Hello, %name%!

Finally, ask for a name, and say 'Hello' to him or her (helloh.txt):

@echo off
echo What is your name?
set /p name=
echo Hello, %name%!

Download the GNU gcc C/C++ compiler (e.g. the latest version of gcc-win64 from SourceForge). Then copy the files and folders into the c:\temp\gcc directory.

Create the 'compileC.bat' file as follows (compileC.txt):

@echo off
c:\temp\gcc\bin\gcc %1.c -o %1

Create the 'hello.c' file which writes the well-known message of 'Hello, World!' after the command prompt (hello.c).

#include <stdio.h>

int main() {
 printf("Hello, World!\n");
 return 0;
 }

Open the command line window (cmd.exe), compile 'hello.c', correct the errors (if any), and then run the created 'hello.exe' file.


Create the 'args.c' file which lists the command line arguments in a console (cmd) window (args.c).

#include <stdio.h>

int main(int argc, char *argv[]) {
 int i;

 for(i=0; i<argc; i++) {
  printf("%d. parameter: %s\n", i, argv[i]);
  }

 return 0;
 }

Open the command line window (cmd.exe), compile 'args.c', correct the errors (if any), and then run the created 'args.exe' file with some command line parameters.

In the C language the 0th command line parameter always exists and contains the name of the source file (e.g. args in this case). Accordingly, the size or length of the array 'argv' is one larger than the number of command line parameters.

Create the 'hellon.c' file which lists the command line arguments in a console (cmd) window (hellon.c).

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
 char s[128]="Anonymous"; 

 if(argc>1) {
  strcpy(s,argv[1]);
  }

 printf("Hello, %s!",s);

 return 0;
 }

Open the command line window (cmd.exe), compile 'hellon.c', correct the errors (if any), and then run the created 'hellon.exe' file with one command line parameter that represents your name.


Create the 'hellox.c' file which reads your name and then displays a welcome message of 'Hello, ...!' after the command prompt (hellox.c).

#include <stdio.h>

int main() {
 char s[128]=""; /* max. 128 chars */

 printf("Your name: ");
 gets(s);
 /* also try this: scanf("%s",s); */
 printf("Hello, %s!",s);
 return 0;
 }

Open the command line window (cmd.exe), compile 'hellox.c', and run the 'hellox.exe' file.

further reading:
Wikipedia: GNU Compiler Collection


Applications of the command line interface II. – Say 'Hello' in C#

We can easily create the 'setpath.bat' file which sets the path of the MS C# compiler located in the .NET Framework:

@echo off
set PATH=c:\Windows\Microsoft.NET\Framework64\v4.0.30319;%PATH%
In the following, we will use three compilers: the 'gcc.exe' for the C language, the 'csc.exe' for the C# language, and the 'javac.exe' (together with the 'java.exe' JVM) for the Java language. The easiest way to use them is to set the default search path so that we can have access to each of the compilers.

Let us add two more paths to the 'setpath.bat' file which set the paths of the C and Java compilers as well (setpath.txt):

@echo off
set x=c:\temp\gcc\bin
set x=c:\Windows\Microsoft.NET\Framework64\v4.0.30319;%x%
set x=c:\temp\jdk-22\bin;%x%

set PATH=%x%;%PATH%

echo new path:
PATH

Note that after downloading the setpath.txt file it should be renamed to setpath.bat.

Create the 'HelloWorld.cs' file written in C# language (HelloWorld.cs):

namespace Hello

{
 class HelloWorld {
  static void Main(string[] args) {
   System.Console.WriteLine("Hello, World!");
   }
 }
}

Open the command line window (cmd.exe), and then run the 'csc.exe' file by compiling the 'HelloWorld.cs' file (csc HelloWorld.cs). Correct the errors (if any), then run the created 'HelloWorld.exe' file.


Create the 'ArgsList.cs' file which lists the command line parameters (ArgsList.cs).

using System;

namespace Hello {

 class ArgsList {
  static void Main(string[] args) {

  for(int i=0; i<args.Length; i++) {
   Console.WriteLine(args[i]);
   }
  }
 }
}

Open the command line window (cmd.exe), compile 'ArgsList.cs', and run the created 'Argslist.exe' file with or without command line parameters.


Create the 'HelloWorldn.cs' file which accepts your name as a command line parameter and then displays a welcome message of 'Hello, ...!' after the command prompt (HelloWorldn.cs).

using System;

namespace Hello {

 class HelloWorldn {
  static void Main(string[] args) {
   string name="Anonymous";

   if(args.Length>0) {
    name=args[0];
    }

   Console.WriteLine(String.Format("Hello, {0}!",name));
   }
  }
 }

Open the command line window (cmd.exe), compile 'HelloWorldn.cs', and run the created 'HelloWorldn.exe' file with and without giving your name as a command line parameter.


Create the 'HelloWorldx.cs' file which reads your name and then displays a welcome message of 'Hello, ...!' after the command prompt (HelloWorldx.cs).

using System;

namespace Hello

{
 class HelloWorldx {
  static void Main(string[] args) {
   string name;

   Console.WriteLine("Who are you?");
   name=Console.ReadLine();

   if(name.Length==0) {
    name="Anonymous";
    }

   Console.WriteLine(String.Format("Hello, {0}!",name));
   }
 }
}

Open the command line window (cmd.exe), compile 'HelloWorldx.cs', and run the created 'HelloWorldx.exe' file.



Applications of the command line interface III – Say 'Hello' in Java

Download the newest Java JDK for Windows (e.g. the jdk-22_windows-x64_bin.zip compressed file from the Oracle website). Then copy the files and folders into the c:\temp\jdk-22 directory.

One way to compile and run a Java program is to create the compileJ.bat batch file which first try to compile the given Java program and, if it is successful, then runs the compiled '.class' file (with a maximum of five command line arguments).

@echo off
c:\temp\jdk-22\bin\javac %1.java
c:\temp\jdk-22\bin\java %1 %2 %3 %4 %5

Another way to compile and run a Java program, which is strongly recommended, is to run the setpath.bat batch file first, and then enter two commands after the command prompt:
    C:\...> javac Filename.java
    C:\...> java Filename

Now create the Hello.java file which writes the well-known message of 'Hello, World!' after the command prompt (Hello.java):

public class Hello {
 public static void main(String[] args) {
  System.out.println("Hello, World!");
  }
 }

Note that the file name (Hello) and the class name (Hello) are the same.

In Java the name of the .java source file must always match the class name.

Open the command line window (cmd.exe), set the default paths (→ setpath.bat; it has to be run only once), compile (→ javac Hello.java), and, if it is successful, then run (→ java Hello) the Hello.java file.


Create the Args.java file which lists the command line parameters (Args.java):

public class Args {

 public static void main(String[] args) {

  for(int i=0; i<args.length; i++) {
   System.out.println(args[i]);
   }
  
  }
 }

Open the command line window (cmd.exe), and then compile and run the Args.java file by giving some command line parameters to test the program.


Create the HelloArg.java file which lists the command line parameters (HelloArg.java):

public class HelloArg {

public static void kiir(String s) {
 System.out.println(s);
 }

public static void kiir(int[] sz) {
 for(int i=0;i<sz.length;i++) {
  System.out.println(sz[i]);
  }
 }

public static void main(String[] args) {
 if(args.length==0) {
  kiir("Missing parameter");
  System.exit(1); // set errorlevel=1
  }
 else {
  kiir("Hello, "+args[0]+"!");
  System.exit(0); // set errorlevel=0
  }
 }
}

Open the command line window (cmd.exe), and then compile and run the HelloArg.java file with or without some command line parameters to test the program. Note that running the HelloArg.java program without command line parameters involves to set the value of the 'errorlevel' variable to 1.


Create the 'Hellon.java' file which accepts your name as a command line parameter and then displays a welcome message of 'Hello, ...!' after the command prompt (Hellon.java):

public class Hellon {

public static void main(String[] args) {
  String name="Anonymous";
  
  if(args.length>0) {
   name=args[0];
   }

  System.out.println("Hello, "+name+"!");
  }
 }

Open the command line window (cmd.exe), and then compile and run the Hellon.java file with or without giving your name as a command line parameter.


Create the 'Hellox.java' file which reads your name and then displays a welcome message of 'Hello, ...!' after the command prompt (Hellox.java):

import java.io.*;

public class Hellox {

public static void main(String[] args) throws IOException {
  String name;
  LineNumberReader in=new LineNumberReader(
                      new BufferedReader(
                      new InputStreamReader(
                      System.in))); 
  
  System.out.println("Who are you?");
  name=in.readLine();

  if(name.length()==0) {
   name="Anonymous";
   }

  System.out.println("Hello, "+name+"!");
  }
 }

Open the command line window (cmd.exe), and then compile and run the Hellox.java file.


Note that the 'LineNumberReader' class can be useful if we want to use the in.getLineNumber() method to count the number of reads. For example, create the 'Helloy.java' file which reads your name again, if you did not enter a real name (Helloy.java):

import java.io.*;

public class Hellox {

public static void main(String[] args) throws IOException {
  String name;
  LineNumberReader in=new LineNumberReader(
                      new BufferedReader(
                      new InputStreamReader(
                      System.in))); 
  
  System.out.println("Who are you?");
  name=in.readLine();

  for(int i=1;i<=3;i++) {
   if(name.length()>0) {
    break;
    }
   System.out.println("I ask you again ("+
         in.getLineNumber()+
         "), who are you?");
   name=in.readLine();
   }

  if(name.length()==0) {
   name="Anonymous";
   }

  System.out.println("Hello, "+name+"!");
  }
 }

Open the command line window (cmd.exe), and then compile and run the Helloy.java file.



Applications of the command line interface IV – List the elements of a series of numbers

Let sn denote the series of 'n' natural numbers (1, 2, ..., n). Enter the number of elements as a command line parameter and list the elements of the series by a C program (numa.c).

#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]) {
 int i,s;
 int n=0;

 if(argc>1) {
  n=atoi(argv[1]);
  }

 if(n<1) {
  n=10;
  printf("The command line argument is invalid. Let n=%d.\n", n);
  }

 s=1;
 for(i=1; i<=n; i++) {
  printf("%d. element: %d\n", i, s);
  s=s+1;
  }

 return 0;
 }

Now enter the number of the elements from the keyboard (numb.c).

#include <stdio.h> 

int main(int argc, char *argv[]) {
 int i,s;
 int n=0;

 printf("Write a number: ");
 i=scanf("%d",&n);

 if(n<1 || i<1) {
  n=10;
  printf("The number is invalid (return code: %d). Let n=%d.\n", i, n);
  }

 s=1;
 for(i=1; i<=n; i++) {
  printf("%d. element: %d\n", i, s);
  s=s+1;
  }

 return 0;
 }

Compile and run the created executable files.


Let sn denote again the series of 'n' natural numbers (1, 2, ..., n). Enter the number of elements as a command line parameter and list the elements of the series by a C# program (NumArg.cs).

using System;

namespace Hello {

 class NumArg {
  static void Main(string[] args) {
  int s;
  int n=0;
  bool b=true;

  if(args.Length>0) {
   b=int.TryParse(args[0], out n);
   }

  if(n<1 || !b) {
   n=10;
   Console.WriteLine(String.Format("The command line argument is invalid. Let n={0}.", n));
   }

  s=1;
  for(int i=1; i<=n; i++) {
   Console.WriteLine(String.Format("{0}. element: {1}", i, s));
   s=s+1;
   }
  }
 }
}

Note that the 'out' keyword in the int.TryParse(...) method results in an output parameter (that is, after 'out n' the result of the conversion will be stored in the given variable 'n').

Now enter the number of the elements from the keyboard and lists the elements of the series by a C# program (NumInp.cs).

using System;

namespace Hello {

 class NumImp {
  static void Main(string[] args) {
  int s;
  int n=0;
  bool b=true;
  string ns;

  Console.WriteLine("Write a number: ");
  ns=Console.ReadLine();
  b=int.TryParse(ns, out n);

  if(n<1 || !b) {
   n=10;
   Console.WriteLine(String.Format("The input is invalid. Let n={0}.", n));
   }

  s=1;
  for(int i=1; i<=n; i++) {
   Console.WriteLine(String.Format("{0}. element: {1}", i, s));
   s=s+1;
   }
  }
 }
}

Compile and run the created executable files.


Let sn denote again the series of 'n' natural numbers (1, 2, ..., n). Enter the number of elements as a command line parameter and list the elements of the series by a Java program (NumArg.java).

public class NumArg {

 public static void main(String[] args) {
  int s;
  int n=0;
  boolean b=true;

  if(args.length>0) {
   try {
    n=Integer.parseInt(args[0]);
    }
   catch(NumberFormatException ex) {
    n=0;
    }
   }

  if(n<1) {
   n=10;
   System.out.println("The command line argument is invalid. Let n="+n+".");
   }

  s=1;
  for(int i=1; i<=n; i++) {
   System.out.println(i+". element: "+s);
   s=s+1;
   }
  }
 }

Now enter the number of the elements from the keyboard and lists the elements of the series by a Java program (NumInp.java).

import java.io.*;

public class NumInp {

 public static void main(String[] args) throws IOException {
  int s;
  int n=0;
  String ns;
  BufferedReader in=new BufferedReader(
                    new InputStreamReader(
                        System.in)); 

  System.out.print("Write a number: ");
  ns=in.readLine();
  try {
    n=Integer.parseInt(ns);
    }
   catch(NumberFormatException ex) {
    n=0;
    }

  if(n<1) {
   n=10;
   System.out.println("The input is invalid. Let n="+n+".");
   }

  s=1;
  for(int i=1; i<=n; i++) {
   System.out.println(i+". element: "+s);
   s=s+1;
   }
  }
 }

Compile and run the created class files.



Applications of the command line interface V – List the elements of the Fibonacci series

Previously we created a batch program that displayed the elements of the Fibonacci series. Now we shall create a C, Java and C# programs to do the same task.

Let sn denote the Fibonacci series (0, 1, 1, 2, 3, 5, 8, ...). Enter the number of the elements to be displayed as a command line parameter and list the elements of the series by a C program (fib.c).

#include <stdio.h> 
#include <stdlib.h> 

int s1,s2;

void sub() {
  int t1,t2;
  printf("%d\n", s2);
  t1=s1;
  t2=s2;
  s2=t1+t2;
  s1=t2;
  }

int main(int argc, char *argv[]) {
 int i;
 int n=0;

 if(argc>1) {
  n=atoi(argv[1]);
  }

 if(n<1) {
  n=10;
  printf("The command line argument is invalid. Let n=%d.\n", n);
  }
 else {
  printf("First %d elements of the Fibonacci series:\n", n);
  }

 s1=0;
 printf("%d\n", s1);
 s2=1;

 for(i=2; i<=n; i++) {
  sub();
  }

 return 0;
 }

Compile and run the created executable file.


Let sn denote again the Fibonacci series (0, 1, 1, 2, 3, 5, 8, ...). Enter the number of the elements to be displayed as a command line parameter and list the elements of the series by a Java program (Fibonacci.java).

public class Fibonacci {
 private static int s1,s2;

 private static void sub() {
  int t1,t2;
  System.out.println(s2);
  t1=s1;
  t2=s2;
  s2=t1+t2;
  s1=t2;
  }

 public static void main(String[] args) {
  int n=0;
  boolean b=true;

  if(args.length>0) {
   try {
    n=Integer.parseInt(args[0]);
    }
   catch(NumberFormatException ex) {
    n=0;
    }
   }

  if(n<1) {
   n=10;
   System.out.println("The command line argument is invalid. Let n="+n+".");
   }

  s1=0;
  System.out.println(s1);
  s2=1;

  for(int i=2; i<=n; i++) {
   sub();
   }
  }
 }

Compile and run the created class file.


Let sn denote again the Fibonacci series (0, 1, 1, 2, 3, 5, 8, ...). Enter the number of the elements to be displayed from keyboard and list the elements of the series by a C# program (Fibonacci.cs).

using System;

namespace Hello {

 class Fibonacci {

  private static int s1,s2;

  private static void sub() {
   int t1,t2;
   Console.WriteLine(s2);
   t1=s1;
   t2=s2;
   s2=t1+t2;
   s1=t2;
   }

  static void Main(string[] args) {
  int n=0;
  bool b=true;
  string ns;

  Console.WriteLine("Write a number: ");
  ns=Console.ReadLine();
  b=int.TryParse(ns, out n);

  if(n<1 || !b) {
   n=10;
   Console.WriteLine(String.Format("The input is invalid. Let n={0}.", n));
   }
  else {
   Console.WriteLine("-----");
   }

  s1=0;
  Console.WriteLine(s1);
  s2=1;

  for(int i=2; i<=n; i++) {
   sub();
   }
  }
 }
}

Now compile and run the created executable file.



Boda István, 2024.