Recent from talks
Contribute something
Nothing was collected or created yet.
Command-line interface
View on Wikipedia
This article needs additional citations for verification. (August 2025) |


A command-line interface (CLI), sometimes called a command-line shell,[1][2] is a means of interacting with software via commands – each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user-friendly alternative to the non-interactive mode available with punched cards.[3]
For nearly three decades, a CLI was the most common interface for software,[disputed – discuss] but today a graphical user interface (GUI) is more common. Nonetheless, many programs such as operating system and software development utilities still provide CLI.
A CLI enables automating programs since commands can be stored in a script file that can be used repeatedly. A script allows its contained commands to be executed as group; as a program; as a command.
A CLI is made possible by command-line interpreters or command-line processors, which are programs that execute input commands.
Alternatives to a CLI include a GUI (including the desktop metaphor such as Windows), text-based menuing (including DOS Shell and IBM AIX SMIT), and keyboard shortcuts.
Comparison to graphical user interfaces
[edit]
Compared with a graphical user interface, a command-line interface requires fewer system resources to implement. Since options to commands are given in a few characters in each command line, an experienced user often finds the options easier to access. Automation of repetitive tasks is simplified by line editing and history mechanisms for storing frequently used sequences; this may extend to a scripting language that can take parameters and variable options. A command-line history can be kept, allowing review or repetition of commands.
A command-line system may require paper or online manuals for the user's reference, although often a help option provides a concise review of the options of a command. The command-line environment may not provide graphical enhancements such as different fonts or extended edit windows found in a GUI. It may be difficult for a new user to become familiar with all the commands and options available, compared with the icons and drop-down menus of a graphical user interface, without reference to manuals.
Types
[edit]Operating system command-line interfaces
[edit]Operating system (OS) command-line interfaces are usually distinct programs supplied with the operating system. A program that implements such a text interface is often called a command-line interpreter, command processor or shell.
Examples of command-line interpreters include Nushell, DEC's DIGITAL Command Language (DCL) in OpenVMS and RSX-11, the various Unix shells (sh, ksh, csh, tcsh, zsh, Bash, etc.), CP/M's CCP, DOS' COMMAND.COM, as well as the OS/2 and the Windows CMD.EXE programs, the latter groups being based heavily on DEC's RSX-11 and RSTS CLIs.[citation needed] Under most operating systems, it is possible to replace the default shell program with alternatives; examples include 4DOS for DOS, 4OS2 for OS/2, and 4NT / Take Command for Windows.
Although the term shell is often used to describe a command-line interpreter, strictly speaking, a shell is a command interpreter and processor and by extension a program that provides an interface (either a user interface (command-line interface, GUI, etc...) or a programming interface) to a command interpreter and processor and to the broad capabilities of the operating system. For example, the default Windows GUI is a shell GUI named EXPLORER.EXE, as defined in the SHELL=EXPLORER.EXE line in the WIN.INI configuration file. This program strictly speaking is a shell GUI and by extension a shell (strictly speaking, the Windows shell is shell32.dll not explorer.exe which is a shell GUI for shell32.dll), but it is not a CLI (command-line interpreter) nor a shell CLI (shell command-line interface).
Application command-line interfaces
[edit]
Application programs (as opposed to operating systems) may also have command-line interfaces.
An application program may support none, any, or all of these three major types of command-line interface mechanisms:
- Parameters: Most command-line interfaces support a means to pass additional information to a program when it is launched.
- Interactive command-line sessions: After launch, a program may provide an operator with an independent means to enter commands.
- Inter-process communication: Most operating systems support means of inter-process communication (for example, standard streams or named pipes). Command lines from client processes may be redirected to a CLI program by one of these methods.
Some applications support a CLI, presenting their own prompt to the user and accepting command lines. Other programs support both a CLI and a GUI. In some cases, a GUI is simply a wrapper around a separate CLI executable file. In other cases, a program may provide a CLI as an optional alternative to its GUI. CLIs and GUIs often support different functionality. For example, all features of MATLAB, a numerical analysis computer program, are available via the CLI, whereas the MATLAB GUI exposes only a subset of features.
In Colossal Cave Adventure from 1975, the user uses a CLI to enter one or two words to explore a cave system.
History
[edit]The command-line interface evolved from a form of communication conducted by people over teleprinter (TTY) machines. Sometimes these involved sending an order or a confirmation using telex. Early computer systems often used teleprinter as the means of interaction with an operator.
The mechanical teleprinter was replaced by a "glass tty", a keyboard and screen emulating the teleprinter. "Smart" terminals permitted additional functions, such as cursor movement over the entire screen, or local editing of data on the terminal for transmission to the computer. As the microcomputer revolution replaced the traditional – minicomputer + terminals – time sharing architecture, hardware terminals were replaced by terminal emulators — PC software that interpreted terminal signals sent through the PC's serial ports. These were typically used to interface an organization's new PC's with their existing mini- or mainframe computers, or to connect PC to PC. Some of these PCs were running Bulletin Board System software.
Early operating system CLIs were implemented as part of resident monitor programs, and could not easily be replaced. The first implementation of the shell as a replaceable component was part of the Multics time-sharing operating system.[4] In 1964, MIT Computation Center staff member Louis Pouzin developed the RUNCOM tool for executing command scripts while allowing argument substitution.[5] Pouzin coined the term shell to describe the technique of using commands like a programming language, and wrote a paper about how to implement the idea in the Multics operating system.[6] Pouzin returned to his native France in 1965, and the first Multics shell was developed by Glenda Schroeder.[5]

The first Unix shell, the V6 shell, was developed by Ken Thompson in 1971 at Bell Labs and was modeled after Schroeder's Multics shell.[7][8] The Bourne shell was introduced in 1977 as a replacement for the V6 shell. Although it is used as an interactive command interpreter, it was also intended as a scripting language and contains most of the features that are commonly considered to produce structured programs. The Bourne shell led to the development of the KornShell (ksh), Almquist shell (ash), and the popular Bourne-again shell (or Bash).[8]
Early microcomputers themselves were based on a command-line interface such as CP/M, DOS or AppleSoft BASIC. During the 1980s and 1990s, the introduction of the Apple Macintosh and of Microsoft Windows on PCs saw the command line interface as the primary user interface replaced by the Graphical User Interface.[9] The command line remained available as an alternative user interface, often used by system administrators and other advanced users for system administration, computer programming and batch processing.
In November 2006, Microsoft released version 1.0 of Windows PowerShell (formerly codenamed Monad), which combined features of traditional Unix shells with their proprietary object-oriented .NET Framework. MinGW and Cygwin are open-source packages for Windows that offer a Unix-like CLI. Microsoft provides MKS Inc.'s ksh implementation MKS Korn shell for Windows through their Services for UNIX add-on.
Since 2001, the Macintosh operating system macOS has been based on a Unix-like operating system called Darwin.[10] On these computers, users can access a Unix-like command-line interface by running the terminal emulator program called Terminal, which is found in the Utilities sub-folder of the Applications folder, or by remotely logging into the machine using ssh. Z shell is the default shell for macOS; Bash, tcsh, and the KornShell are also provided. Before macOS Catalina, Bash was the default.
Usage
[edit]A CLI is used whenever a large vocabulary of commands or queries, coupled with a wide (or arbitrary) range of options, can be entered more rapidly as text than with a pure GUI. This is typically the case with operating system command shells. CLIs are also used by systems with insufficient resources to support a graphical user interface. Some computer language systems (such as Python,[11] Forth, LISP, Rexx, and many dialects of BASIC) provide an interactive command-line mode to allow for rapid evaluation of code.
CLIs are often used by programmers and system administrators, in engineering and scientific environments, and by technically advanced personal computer users.[12] CLIs are also popular among people with visual disabilities since the commands and responses can be displayed using refreshable Braille displays.
Anatomy of a shell CLI
[edit]The general pattern of a command line is:[13][14]
prompt command param1 param2 param3 … paramN
- prompt — output by the program to indicate that its ready for input; a prompt may include contextual information and often ends with a symbol that provides a visual cue that input is expected
- command — input by the user, a command is usually one of two classes:
- Internal commands are recognized and processed by the command line interpreter. Internal commands are also called built-in commands.[15]
- External commands run executables found in separate executable files. The command line interpreter searches for executable files with names matching the external command.[16][17]
- param1 …paramN — parameters provided by the user. The format and meaning of the parameters depends upon the command. In the case of external commands, the values of the parameters are delivered to the program as it is launched by the OS. Parameters may be either arguments or options.
In this format, the delimiters between command-line elements are whitespace characters and the end-of-line delimiter is the newline delimiter. This is a widely used (but not universal) convention.
A CLI can generally be considered as consisting of syntax and semantics. The syntax is the grammar that all commands must follow. In the case of operating systems, DOS and Unix each define their own set of rules that all commands must follow. In the case of embedded systems, each vendor, such as Nortel, Juniper Networks or Cisco Systems, defines their own proprietary set of rules. These rules also dictate how a user navigates through the system of commands. The semantics define what sort of operations are possible, on what sort of data these operations can be performed, and how the grammar represents these operations and data—the symbolic meaning in the syntax.
Two different CLIs may agree on either syntax or semantics, but it is only when they agree on both that they can be considered sufficiently similar to allow users to use both CLIs without needing to learn anything, as well as to enable re-use of scripts.
A simple CLI will display a prompt, accept a command line typed by the user terminated by the Enter key, then execute the specified command and provide textual display of results or error messages. Advanced CLIs will validate, interpret and parameter-expand the command line before executing the specified command, and optionally capture or redirect its output.
Unlike a button or menu item in a GUI, a command line is typically self-documenting,[18] stating exactly what the user wants done. In addition, command lines usually include many defaults that can be changed to customize the results. Useful command lines can be saved by assigning a character string or alias to represent the full command, or several commands can be grouped to perform a more complex sequence – for instance, compile the program, install it, and run it — creating a single entity, called a command procedure or script which itself can be treated as a command. These advantages mean that a user must figure out a complex command or series of commands only once, because they can be saved, to be used again.
The commands given to a CLI shell are often in one of the following forms:
doSomething how toFilesdoSomething how sourceFile destinationFiledoSomething how < inputFile > outputFiledoSomething how | doSomething how | doSomething how > outputFile
where doSomething is, in effect, a verb, how an adverb (for example, should the command be executed verbosely or quietly) and toFiles an object or objects (typically one or more files) on which the command should act. The > in the third example is a redirection operator, telling the command-line interpreter to send the output of the command not to its own standard output (the screen) but to the named file. This will overwrite the file. Using >> will redirect the output and append it to the file. Another redirection operator is the vertical bar (|), which creates a pipeline where the output of one command becomes the input to the next command.[19]
CLI and resource protection
[edit]On some systems, such as Unix-like systems or Windows, one can modify the set of available commands by modifying which paths appear in the PATH environment variable or its equivalent. On Unix-like systems, commands also need be marked as executable files. The directories in the path variable are searched in the order they are given. By re-ordering the path, one can run e.g. \OS2\MDOS\E.EXE instead of \OS2\E.EXE, when the default is the opposite. Renaming of the executables also works: people often rename their favourite editor to EDIT, for example.
The command line allows one to restrict available commands, such as access to advanced internal commands. The Bourne shell and workalikes such as Bash can be run as a restricted shell; among other things, this prohibits the user from modifying the PATH environment variable, so that if PATH is set to include only directories that contain only permissible commands, the user will only be able to run those commands. The Windows CMD.EXE also supports restricting available commands. Often, shareware programs will limit the range of commands, including printing a command 'your administrator has disabled running batch files' from the prompt.[clarification needed]
Some CLIs, such as those in network routers, have a hierarchy of modes, with a different set of commands supported in each mode. The set of commands are grouped by association with security, system, interface, etc. In these systems the user might traverse through a series of sub-modes. For example, if the CLI had two modes called interface and system, the user might use the command interface to enter the interface mode. At this point, commands from the system mode may not be accessible until the user exits the interface mode and enters the system mode.
Command prompt
[edit]
A command prompt (or just prompt) is a sequence of (one or more) characters used in a command-line interface to indicate readiness to accept commands. It literally prompts the user to take action. A prompt usually ends with one of the characters $, %, #,[20][21] :, > or -[22] and often includes other information, such as the path of the current working directory and the hostname.
On many Unix and derivative systems, the prompt commonly ends in $ or % if the user is a normal user, but in # if the user is a superuser ("root" in Unix terminology).
End-users can often modify prompts. Depending on the environment, they may include colors, special characters, and other elements (like variables and functions for the current time, user, shell number or working directory) in order, for instance, to make the prompt more informative or visually pleasing, to distinguish sessions on various machines, or to indicate the current level of nesting of commands. On some systems, special tokens in the definition of the prompt can be used to cause external programs to be called by the command-line interpreter while displaying the prompt.
In DOS' COMMAND.COM and in Windows NT's cmd.exe users can modify the prompt by issuing a PROMPT command or by directly changing the value of the corresponding %PROMPT% environment variable. The default of most modern systems, the C:\> style is obtained, for instance, with PROMPT $P$G. The default of older DOS systems, C> is obtained by just PROMPT, although on some systems this produces the newer C:\> style, unless used on floppy drives A: or B:; on those systems PROMPT $N$G can be used to override the automatic default and explicitly switch to the older style.
Many Unix systems feature the $PS1 variable (Prompt String 1),[23] although other variables also may affect the prompt (depending on the shell used). In the Bash shell, a prompt of the form:
[time] user@host: work_dir $
could be set by issuing the command
export PS1='[\t] \u@\H: \W $'
In zsh the $RPROMPT variable controls an optional prompt on the right-hand side of the display. It is not a real prompt in that the location of text entry does not change. It is used to display information on the same line as the prompt, but right-justified.
In RISC OS the command prompt is a * symbol, and thus (OS) CLI commands are often referred to as star commands.[24] One can also access the same commands from other command lines (such as the BBC BASIC command line), by preceding the command with a *.
Arguments
[edit]
A command-line argument or parameter is an item of information provided to a program when it is started.[25] A program can have many command-line arguments that identify sources or destinations of information, or that alter the operation of the program.
When a command processor is active a program is typically invoked by typing its name followed by command-line arguments (if any). For example, in Unix and Unix-like environments, an example of a command-line argument is:
rm file.s
file.s is a command-line argument which tells the program rm to remove the file named file.s.
Some programming languages, such as C, C++ and Java, allow a program to interpret the command-line arguments by handling them as string parameters in the main function.[26][27] Other languages, such as Python, expose operating system specific API (functionality) through sys module, and in particular sys.argv for command-line arguments.
In Unix-like operating systems, a single hyphen used in place of a file name is a special value specifying that a program should handle data coming from the standard input or send data to the standard output.
Command-line option
[edit]A command-line option or simply option (also known as a flag or switch) modifies the operation of a command; the effect is determined by the command's program. Options follow the command name on the command line, separated by spaces. A space before the first option is not always required, such as Dir/? and DIR /? in DOS, which have the same effect[22] of listing the DIR command's available options, whereas dir --help (in many versions of Unix) does require the option to be preceded by at least one space (and is case-sensitive).
The format of options varies widely between operating systems. In most cases, the syntax is by convention rather than an operating system requirement; the entire command line is simply a string passed to a program, which can process it in any way the programmer wants, so long as the interpreter can tell where the command name ends and its arguments and options begin.
A few representative samples of command-line options, all relating to listing files in a directory, to illustrate some conventions:
| Operating system | Command | Valid alternative | Notes |
|---|---|---|---|
| OpenVMS | directory/owner |
Dir /Owner |
instruct the directory command to also display the ownership of the files. Note the Directory command name is not case sensitive, and can be abbreviated to as few letters as required to remain unique. |
| Windows | DIR/Q/O:S d* |
dir /q d* /o:s |
display ownership of files whose names begin with d (or D), sorted by size, smallest first. Note spaces around argument d* are required. |
| Unix-like systems | ls -lS D* |
ls -S -l D* |
display in long format files and directories whose names begin with D (but not d), sorted by size (largest first). Note spaces are required around all arguments and options, but some can be run together, e.g. -lS is the same as -l -S. |
| Data General RDOS CLI | list/e/s 04-26-80/b |
List /S/E 4-26-80/B |
list every attribute for files created before 26 April 1980. Note the /B at the end of the date argument is a local switch, that modifies the meaning of that argument, while /S and /E are global switches, i.e. apply to the whole command. |
| VM/CMS CLI | LISTFILE (FULLDATE) |
l(ful |
includes the date the file was last written in the list. Note the LISTFILE command name is not case sensitive, and can be abbreviated to as few letters as required to remain unique. |
Abbreviating commands
[edit]In Multics, command-line options and subsystem keywords may be abbreviated. This idea appears to derive from the PL/I programming language, with its shortened keywords (e.g., STRG for STRINGRANGE and DCL for DECLARE). For example, in the Multics forum subsystem, the -long_subject parameter can be abbreviated -lgsj. It is also common for Multics commands to be abbreviated, typically corresponding to the initial letters of the words that are strung together with underscores to form command names, such as the use of did for delete_iacl_dir.
In some other systems abbreviations are automatic, such as permitting enough of the first characters of a command name to uniquely identify it (such as SU as an abbreviation for SUPERUSER) while others may have some specific abbreviations pre-programmed (e.g. MD for MKDIR in COMMAND.COM) or user-defined via batch scripts and aliases (e.g. alias md mkdir in tcsh).
Option conventions in DOS, Windows, OS/2
[edit]On DOS, OS/2 and Windows, different programs called from their COMMAND.COM or CMD.EXE (or internal their commands) may use different syntax within the same operating system. For example:
- Options may be indicated by either of the switch characters:
/,-, or either may be allowed. See below. - They may or may not be case-sensitive.
- Sometimes options and their arguments are run together, sometimes separated by whitespace, and sometimes by a character, typically
:or=; thusProg -fFilename,Prog -f Filename,Prog -f:Filename,Prog -f=Filename. - Some programs allow single-character options to be combined;[22] others do not. The switch
-fAmay mean the same as-f -A,[22] or it may be incorrect, or it may even be a valid but different parameter.
In DOS, OS/2 and Windows, the forward slash (/) is most prevalent, although the hyphen-minus is also sometimes used. In many versions of DOS (MS-DOS/PC DOS 2.xx and higher, all versions of DR-DOS since 5.0, as well as PTS-DOS, Embedded DOS, FreeDOS and RxDOS) the switch character (sometimes abbreviated switchar or switchchar) to be used is defined by a value returned from a system call (INT 21h/AX=3700h). The default character returned by this API is /, but can be changed to a hyphen-minus on the above-mentioned systems, except for under Datalight ROM-DOS and MS-DOS/PC DOS 5.0 and higher, which always return / from this call (unless one of many available TSRs to reenable the SwitChar feature is loaded). In some of these systems (MS-DOS/PC DOS 2.xx, DOS Plus 2.1, DR-DOS 7.02 and higher, PTS-DOS, Embedded DOS, FreeDOS and RxDOS), the setting can also be pre-configured by a SWITCHAR directive in CONFIG.SYS. General Software's Embedded DOS provides a SWITCH command for the same purpose, whereas 4DOS allows the setting to be changed via SETDOS /W:n.[28] Under DR-DOS, if the setting has been changed from /, the first directory separator \ in the display of the PROMPT parameter $G will change to a forward slash / (which is also a valid directory separator in DOS, FlexOS, 4680 OS, 4690 OS, OS/2 and Windows) thereby serving as a visual clue to indicate the change.[22] Also, the current setting is reflected also in the built-in help screens.[22] Some versions of DR-DOS COMMAND.COM also support a PROMPT token $/ to display the current setting. COMMAND.COM since DR-DOS 7.02 also provides a pseudo-environment variable named %/% to allow portable batchjobs to be written.[29][30] Several external DR-DOS commands additionally support an environment variable %SWITCHAR% to override the system setting.
However, many programs are hardwired to use / only, rather than retrieving the switch setting before parsing command-line arguments. A very small number, mainly ports from Unix-like systems, are programmed to accept - even if the switch character is not set to it (for example netstat and ping, supplied with Microsoft Windows, will accept the /? option to list available options, and yet the list will specify the - convention).
Option conventions in Unix-like systems
[edit]This section needs additional citations for verification. (July 2021) |
In Unix-like systems, the ASCII hyphen-minus begins options; the new (and GNU) convention is to use two hyphens then a word (e.g. --create) to identify the option's use while the old convention (and still available as an option for frequently used options) is to use one hyphen then one letter (e.g., -c); if one hyphen is followed by two or more letters it may mean two options are being specified, or it may mean the second and subsequent letters are a parameter (such as filename or date) for the first option.[31]
Two hyphen-minus characters without following letters (--) may indicate that the remaining arguments should not be treated as options, which is useful for example if a file name itself begins with a hyphen, or if further arguments are meant for an inner command (e.g., sudo). Double hyphen-minuses are also sometimes used to prefix long options where more descriptive option names are used. This is a common feature of GNU software. The getopt function and program, and the getopts command are usually used for parsing command-line options.
Unix command names, arguments and options are case-sensitive (except in a few examples, mainly where popular commands from other operating systems have been ported to Unix).
Option conventions in other systems
[edit]FlexOS, 4680 OS and 4690 OS use -.
CP/M typically used [.
Conversational Monitor System (CMS) uses a single left parenthesis to separate options at the end of the command from the other arguments. For example, in the following command the options indicate that the target file should be replaced if it exists, and the date and time of the source file should be retained on the copy:
COPY source file a target file b (REPLACE OLDDATE)
Data General's CLI under their RDOS, AOS, etc. operating systems, as well as the version of CLI that came with their Business Basic, uses only / as the switch character, is case-insensitive, and allows local switches on some arguments to control the way they are interpreted, such as MAC/U LIB/S A B C $LPT/L has the global option U to the macro assembler command to append user symbols, but two local switches, one to specify LIB should be skipped on pass 2 and the other to direct listing to the printer, $LPT.
Built-in usage help
[edit]One of the criticisms of a CLI is the lack of cues to the user as to the available actions.[citation needed] In contrast, GUIs usually inform the user of available actions with menus, icons, or other visual cues.[citation needed] To overcome this limitation, many CLI programs display a usage message, typically when invoked with no arguments or one of ?, -?, -h, -H, /?, /h, /H, /Help, -help, or --help.[22][32][33]
However, entering a program name without parameters in the hope that it will display usage help can be hazardous, as programs and scripts for which command line arguments are optional will execute without further notice.
Although desirable at least for the help parameter, programs may not support all option lead-in characters exemplified above.
Under DOS, where the default command-line option character can be changed from / to -, programs may query the SwitChar API in order to determine the current setting. So, if a program is not hardwired to support them all, a user may need to know the current setting even to be able to reliably request help.
If the SwitChar has been changed to - and therefore the / character is accepted as alternative path delimiter also at the DOS command line, programs may misinterpret options like /h or /H as paths rather than help parameters.[22] However, if given as first or only parameter, most DOS programs will, by convention, accept it as request for help regardless of the current SwitChar setting.[22][28]
In some cases, different levels of help can be selected for a program. Some programs supporting this allow to give a verbosity level as an optional argument to the help parameter (as in /H:1, /H:2, etc.) or they give just a short help on help parameters with question mark and a longer help screen for the other help options.[34]
Depending on the program, additional or more specific help on accepted parameters is sometimes available by either providing the parameter in question as an argument to the help parameter or vice versa (as in /H:W or in /W:? (assuming /W would be another parameter supported by the program)).[35][36][33][32][34][nb 1]
In a similar fashion to the help parameter, but much less common, some programs provide additional information about themselves (like mode, status, version, author, license or contact information) when invoked with an about parameter like -!, /!, -about, or --about.[32]
Since the ? and ! characters typically also serve other purposes at the command line, they may not be available in all scenarios, therefore, they should not be the only options to access the corresponding help information.

If more detailed help is necessary than provided by a program's built-in internal help, many systems support a dedicated external help command" command (or similar), which accepts a command name as calling parameter and will invoke an external help system.
In the DR-DOS family, typing /? or /H at the COMMAND.COM prompt instead of a command itself will display a dynamically generated list of available internal commands;[22] 4DOS and NDOS support the same feature by typing ? at the prompt[28] (which is also accepted by newer versions of DR-DOS COMMAND.COM); internal commands can be individually disabled or reenabled via SETDOS /I.[28] In addition to this, some newer versions of DR-DOS COMMAND.COM also accept a ?% command to display a list of available built-in pseudo-environment variables. Besides their purpose as quick help reference this can be used in batchjobs to query the facilities of the underlying command-line processor.[22]
Command description syntax
[edit]Built-in usage help and man pages commonly employ a small syntax to describe the valid command form:[37][38][39][nb 2]
- angle brackets for required parameters:
ping <hostname> - square brackets for optional parameters:
mkdir [-p] <dirname> - ellipses for repeated items:
cp <source1> [source2…] <dest> - vertical bars for choice of items:
netstat {-t|-u}
Notice that these characters have different meanings than when used directly in the shell. Angle brackets may be omitted when confusing the parameter name with a literal string is not likely.
The space character
[edit]In many areas of computing, but particularly in the command line, the space character can cause problems as it has two distinct and incompatible functions: as part of a command or parameter, or as a parameter or name separator. Ambiguity can be prevented either by prohibiting embedded spaces in file and directory names in the first place (for example, by substituting them with underscores _), or by enclosing a name with embedded spaces between quote characters or using an escape character before the space, usually a backslash (\). For example
Long path/Long program name Parameter one Parameter two…
is ambiguous (is program name part of the program name, or two parameters?); however
Long_path/Long_program_name Parameter_one Parameter_two…,LongPath/LongProgramName ParameterOne ParameterTwo…,"Long path/Long program name" "Parameter one" "Parameter two"…
and
Long\ path/Long\ program\ name Parameter\ one Parameter\ two…
are not ambiguous. Unix-based operating systems minimize the use of embedded spaces to minimize the need for quotes. In Microsoft Windows, one often has to use quotes because embedded spaces (such as in directory names) are common.
Command-line interpreter
[edit]Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a command. Because it must satisfy both the interactive and programming aspects of command execution, it is a strange language, shaped as much by history as by design.
The term command-line interpreter is applied to computer programs designed to interpret a sequence of lines of text which may be entered by a user, read from a file or another kind of data stream. The context of interpretation is usually one of a given operating system or programming language.
Command-line interpreters allow users to issue various commands in a very efficient (and often terse) way. This requires the user to know the names of the commands and their parameters, and the syntax of the language that is interpreted.
The Unix #! mechanism and OS/2 EXTPROC command facilitate the passing of batch files to external processors. One can use these mechanisms to write specific command processors for dedicated uses, and process external data files which reside in batch files.
Many graphical interfaces, such as the OS/2 Presentation Manager and early versions of Microsoft Windows use command lines to call helper programs to open documents and programs. The commands are stored in the graphical shell[clarification needed] or in files like the registry or the OS/2 OS2USER.INI file.
Early history
[edit]

The earliest computers did not support interactive input/output devices, often relying on sense switches and lights to communicate with the computer operator. This was adequate for batch systems that ran one program at a time, often with the programmer acting as operator. This also had the advantage of low overhead, since lights and switches could be tested and set with one machine instruction. Later a single system console was added to allow the operator to communicate with the system.
From the 1960s onwards, user interaction with computers was primarily by means of command-line interfaces, initially on machines like the Teletype Model 33 ASR, but then on early CRT-based computer terminals such as the VT52.
All of these devices were purely text based, with no ability to display graphic or pictures.[nb 3] For business application programs, text-based menus were used, but for more general interaction the command line was the interface.
Around 1964 Louis Pouzin introduced the concept and the name shell in Multics, building on earlier, simpler facilities in the Compatible Time-Sharing System (CTSS).[41][better source needed]
From the early 1970s the Unix operating system adapted the concept of a powerful command-line environment, and introduced the ability to pipe the output of one command in as input to another. Unix also had the capability to save and re-run strings of commands as shell scripts which acted like custom commands.
The command line was also the main interface for the early home computers such as the Commodore PET, Apple II and BBC Micro – almost always in the form of a BASIC interpreter. When more powerful business-oriented microcomputers arrived with CP/M and later DOS computers such as the IBM PC, the command line began to borrow some of the syntax and features of the Unix shells such as globbing and piping of output.
The command line was first seriously challenged by the PARC GUI approach used in the 1983 Apple Lisa and the 1984 Apple Macintosh. A few computer users used GUIs such as GEOS and Windows 3.1 but the majority of IBM PC users did not replace their COMMAND.COM shell with a GUI until Windows 95 was released in 1995.[42][43]
Modern usage as an operating system shell
[edit]While most non-expert computer users now use a GUI almost exclusively, more advanced users have access to powerful command-line environments:
- Unix-like systems include the Bourne shell and compatible shells such as Bash, and other Unix shells.
- FreeBSD uses tcsh as its default interactive shell for the superuser, and ash as default scripting shell.
- Many Linux distributions have Bash.
- Apple macOS and some Linux distributions use zsh. Previously, macOS used tcsh and Bash.
- Embedded Linux (and other embedded Unix-like) systems often use ash, as part of Busybox.
- Android uses the mksh shell,[44][45] which replaces a shell derived from ash[46] that was used in older Android versions, supplemented with commands from the separate toolbox[47] binary.
- OpenVMS uses the DIGITAL Command Language (DCL).
- Unix command shells have been ported to OpenVMS.
- DOS and Windows have several command-line environments
- COMMAND.COM is the command-line interpreter of MS-DOS, IBM PC DOS, and Windows 9x, as well as clones such as DR-DOS, SISNE plus, PTS-DOS, ROM-DOS, and FreeDOS.
- Windows NT has cmd.exe, and later versions have PowerShell
- The Windows Resource Kit and Windows Services for UNIX include Korn and the Bourne shells along with a Perl interpreter (Services for UNIX contains ActiveState ActivePerl in later versions and Interix for versions 1 and 2 and a shell compiled by Microsoft)
- Windows users might use the CScript interface to alternate programs, from the command line. Implementations of the Unix shell are also available as part of the POSIX sub-system,[48] Cygwin, MKS Toolkit, UWIN, Hamilton C shell and other software packages. Available shells for these interoperability tools include csh, ksh, sh, Bash, rsh, tclsh and less commonly zsh, psh
- DCL has been ported to Windows systems at least three times, including PC-DCL and Acceler8 DCL Lite.
- Yet another cmd.exe is a stripped-down shell for Windows CE 3.0.
- An MS-DOS type interpreter called PocketDOS has been ported to Windows CE machines; the most recent release is almost identical to MS-DOS 6.22 and can also run Windows 1, 2, and 3.0, QBasic and other development tools, 4NT and 4DOS. The latest release includes several shells, namely MS-DOS 6.22, PC DOS 7, DR DOS 3.xx, and others.
- IBM OS/2 (and derivatives such as eComStation and ArcaOS) has the cmd.exe processor. This copies the COMMAND.COM commands, with extensions to REXX.
- Implementations of PHP have a shell for interactive use called php-cli.
- Standard Tcl/Tk has two interactive shells, Tclsh and Wish, the latter being the GUI version.
- Python, Ruby, Lua, XLNT, and other interpreters also have command shells for interactive use.
- HarmonyOS, OpenHarmony and Oniro uses the commands from third party toolbox compatibility system attached to Linux kernel of the subsystem alongside default Shell with exec commands.[49][50]
- Routers with Cisco IOS,[51] Junos[52] and many others are commonly configured from the command line.
- The Plan 9 operating system uses the rc shell, which is similar in design to the Bourne shell.
Scripting
[edit]Most command-line interpreters support scripting, to various extents. (They are, after all, interpreters of an interpreted programming language, albeit in many cases the language is unique to the particular command-line interpreter.) They will interpret scripts (variously termed shell scripts or batch files) written in the language that they interpret. Some command-line interpreters also incorporate the interpreter engines of other languages, such as REXX, in addition to their own, allowing the executing of scripts, in those languages, directly within the command-line interpreter itself.
Conversely, scripting programming languages, in particular those with an eval function (such as REXX, Perl, Python, Ruby or Jython), can be used to implement command-line interpreters and filters. For a few operating systems, most notably DOS, such a command interpreter provides a more flexible command-line interface than the one supplied. In other cases, such a command interpreter can present a highly customised user interface employing the user interface and input/output facilities of the language.
Other command-line interfaces
[edit]The command line provides an interface between programs as well as the user. In this sense, a command line is an alternative to a dialog box. Editors and databases present a command line, in which alternate command processors might run. On the other hand, one might have options on the command line, which opens a dialog box. The latest version of 'Take Command' has this feature. DBase used a dialog box to construct command lines, which could be further edited before use.
Programs like BASIC, diskpart, Edlin, and QBASIC all provide command-line interfaces, some of which use the system shell. Basic is modeled on the default interface for 8-bit Intel computers. Calculators can be run as command-line or dialog interfaces.
Emacs provides a command-line interface in the form of its minibuffer. Commands and arguments can be entered using Emacs standard text editing support, and output is displayed in another buffer.
There are a number of text mode games, like Adventure or King's Quest 1-3, which relied on the user typing commands at the bottom of the screen. One controls the character by typing commands like 'get ring' or 'look'. The program returns a text which describes how the character sees it, or makes the action happen. The text adventure The Hitchhiker's Guide to the Galaxy, a piece of interactive fiction based on Douglas Adam's book of the same name, is a teletype-style command-line game.
The most notable of these interfaces is the standard streams interface, which allows the output of one command to be passed to the input of another. Text files can serve either purpose as well. This provides the interfaces of piping, filters and redirection. Under Unix, devices are files too, so the normal type of file for the shell used for stdin, stdout and stderr is a tty device file.
Another command-line interface allows a shell program to launch helper programs, either to launch documents or start a program. The command is processed internally by the shell, and then passed on to another program to launch the document. The graphical interface of Windows and OS/2 rely heavily on command lines passed through to other programs – console or graphical, which then usually process the command line without presenting a user-console.
Programs like the OS/2 E editor and some other IBM editors, can process command lines normally meant for the shell, the output being placed directly in the document window.
A web browser's URL input field can be used as a command line. It can be used to launch web apps, access browser configuration, as well as perform a search. Google, which has been called "the command line of the internet" will perform a domain-specific search when it detects search parameters in a known format.[53] This functionality is present whether the search is triggered from a browser field or on Google's website.
There are JavaScript libraries that allow to write command line applications in browser as standalone Web apps or as part of bigger application.[54] An example of such a website is the CLI interface to DuckDuckGo.[55] There are also web-based SSH applications that allow access to a server’s command-line interface from a browser.
Many PC video games feature a command line interface often referred to as a console. It is typically used by the game developers during development and by mod developers for debugging purposes as well as for cheating or skipping parts of the game.
See also
[edit]Notes
[edit]- ^ An example is the comprehensive internal help system of the DR-DOS 7.03 DEBUG command, which can be invoked via
??at the debug prompt (rather than only the default?overview). Specific help pages can be selected via?n(wherenis the number of the page). Additionally, help for specific commands can be displayed by specifying the command name after?, f.e.?Dwill invoke help for the various dump commands (likeDetc.). Some of these features were already supported by the DR DOS 3.41 SID86 and GEMSID. - ^ Notable difference for describing the command syntax of DOS-like operating systems: Windows Server 2003 R2 documentation uses italic letters for "information that the user must supply", but Windows Server 2008 documentation uses angle brackets. Italics can not be displayed by the internal help command, while there is no problem with angle brackets.
- ^ With the exception of ASCII art.
References
[edit]- ^ "Command Line Shell For SQLite".
- ^ "CAS - Configuring Commandline Shell".
- ^ "The evolution of command line interface (CLI): A historical insight | Contentstack". www.contentstack.com. Retrieved 2025-01-28.
- ^ "Unix Shells". Archived from the original on 2007-11-08.
the notion of having a replaceable "command shell" rather than a "monitor" tightly integrated with the OS kernel tends to be attributed to Multics.
- ^ a b "The Origin of the Shell". www.multicians.org. Archived from the original on 2017-12-21. Retrieved 2017-04-12.
- ^ Metz, Cade (2013-01-03). "Say Bonjour to the Internet's Long-Lost French Uncle". Wired. Retrieved 2017-07-31.
- ^ Mazières, David (Fall 2004). "MULTICS - The First Seven Years". Advanced Operating Systems. Stanford Computer Science Department. Archived from the original on 2014-11-23. Retrieved 2017-08-01.
- ^ a b Jones, M. (2011-12-06). "Evolution of shells in Linux". developerWorks. IBM. Archived from the original on 2017-07-08. Retrieved 2017-08-01.
- ^ "Graphical User Interface History". KASS. Retrieved 2024-03-24.
- ^ Singh, Amit (2006-06-19). Mac OS X Internals: A Systems Approach. Addison-Wesley Professional. ISBN 978-0-13-270226-3.
- ^ "1. Command line and environment". Python documentation. Retrieved 2024-08-05.
- ^ "What is a CLI? - Command Line Interface Explained - AWS". Amazon Web Services, Inc. Retrieved 2025-01-28.
- ^ "GNU BASH Reference". Archived from the original on 2010-12-03. Retrieved 2015-12-20.
- ^ "Microsoft Windows Command Shell Overview". 2009-09-11. Archived from the original on 2015-09-05. Retrieved 2015-07-12.
- ^ "Shell Built-in Commands List". Linux Handbook. 2023-07-05. Retrieved 2024-08-05.
- ^ B, Jason. "How to set your $PATH variable in Linux | Opensource.com". opensource.com. Retrieved 2024-08-05.
- ^ JasonGerend (2023-02-03). "path". learn.microsoft.com. Retrieved 2024-08-05.
- ^ "Command Line Interface (CLI)". tutorials.cloudfoundry.org. Retrieved 2025-01-28.
- ^ "Learning the bash Shell, Second Edition [Book]". www.oreilly.com. Retrieved 2024-08-05.
- ^ SID Users Guide (PDF). Digital Research. 1978. 595-2549. Archived (PDF) from the original on 2019-10-20. Retrieved 2020-02-06. (4+69 pages)
- ^ SID-86 User's Guide for CP/M-86 (2 ed.). Digital Research. August 1982 [March 1982]. SID86UG.WS4. Archived from the original on 2019-10-20. Retrieved 2020-02-06. [1] (NB. A retyped version of the manual by Emmanuel Roche with Q, SR, and Z commands added.)
- ^ a b c d e f g h i j k Paul, Matthias R. (1997-07-30). "NWDOS-TIPs – Tips & Tricks rund um Novell DOS 7, mit Blick auf undokumentierte Details, Bugs und Workarounds". MPDOSTIP. Release 157 (in German) (3 ed.). Archived from the original on 2017-09-10. Retrieved 2014-09-06. (NB. NWDOSTIP.TXT is a comprehensive work on Novell DOS 7 and OpenDOS 7.01, including the description of many undocumented features and internals. It is part of the author's yet larger MPDOSTIP.ZIP collection maintained up to 2001 and distributed on many sites at the time. The provided link points to a HTML-converted older version of the NWDOSTIP.TXT file.)
- ^ Parker, Steve (2011). "Chapter 11: Choosing and using shells". Shell Scripting: Expert Recipes for Linux, Bash and more. Programmer to programmer. Indianapolis, USA: John Wiley & Sons. p. 262. ISBN 978-111816632-1.
The shell has four different command prompts, called PS1, P52, P53, and PS4. PS stands for Prompt String.
- ^ RISC OS 3 User Guide (PDF). Acorn Computers Limited. 1992-03-01. p. 125. Archived (PDF) from the original on 2017-01-09. Retrieved 2017-04-12.
- ^ nguyen-dows (2024-05-29). "Windows Terminal command line arguments". learn.microsoft.com. Retrieved 2024-08-05.
- ^ "Command Line Arguments in C". www.w3schools.in. Retrieved 2024-08-05.
- ^ "Command Line Arguments in Java". GeeksforGeeks. 2016-08-16. Retrieved 2024-08-05.
- ^ a b c d Brothers, Hardin; Rawson, Tom; Conn, Rex C.; Paul, Matthias R.; Dye, Charles E.; Georgiev, Luchezar I. (2002-02-27). 4DOS 8.00 online help.
- ^ Paul, Matthias R. (1998-01-09). DELTREE.BAT R1.01 Extended file and directory delete. Caldera, Inc. Archived from the original on 2019-04-08. Retrieved 2019-04-08.
- ^ DR-DOS 7.03 WHATSNEW.TXT — Changes from DR-DOS 7.02 to DR-DOS 7.03. Caldera, Inc. 1998-12-24. Archived from the original on 2019-04-08. Retrieved 2019-04-08.
- ^ "Argument Syntax (The GNU C Library)". gnu.org. Archived from the original on 2021-06-18. Retrieved 2021-07-09.
- ^ a b c Paul, Matthias R. (2002-05-13). "[fd-dev] mkeyb". freedos-dev. Archived from the original on 2018-09-10. Retrieved 2018-09-10.
[…] CPI /H […] CPI [@] [@] [/?|/Help[:topic]] [/!|/About] […] [?|&] […] /?, /Help Display this help screen or specific help for a topic (+) […] /!, /About Display the 'About' info screen […] /Cpifile (+) .CPI/.CP file name <EGA.CPI>; extension: <.CPI>; CPI.EXE=StdIn […] /Report Report file name <'
'=StdOut>; extension: <.RPT> […] /Style (+) Export <0>-6=BIN-raw/ROM/RAM/PSF0/1/SH/CHED; 7-12/13-18/19-24=ASM-hex/dec/bin/ip/il/p/l/mp/ml […] CPI /H:C […] Overview on codepage file parameter usage: […] CPI /H:S […] Overview on /Style parameters: […] ?, & Online edit mode (prompts for additional parameter input) […] - ^ a b Paul, Matthias R. (2002-01-09). "SID86". Newsgroup: comp.os.cpm. Retrieved 2018-04-08.
[…] Since the DR-DOS 7.03 DEBUG is still based on the old SID86.EXE, I suggest to run DEBUG 1.51 and enter the extended help system with ?? from the debug prompt. This will give you eight screens full of syntax and feature help. Some of these features were also supported by older issues. […]
- ^ a b Paul, Matthias R.; Frinke, Axel C. (2006-01-16). FreeKEYB - Advanced international DOS keyboard and console driver (User Manual) (v7 preliminary ed.).
- ^ CCI Multiuser DOS 7.22 GOLD Online Documentation. Concurrent Controls, Inc. (CCI). 1997-02-10. HELP.HLP. (NB. The symbolic instruction debugger SID86 provides a short help screen on
?and comprehensive help on??.) - ^ Paul, Matthias R. (1997-05-24) [1991]. "DRDOSTIP.TXT – Tips und Tricks für DR DOS 3.41 - 5.0". MPDOSTIP (in German) (47 ed.). Archived from the original on 2016-11-07. Retrieved 2016-11-07.
- ^ "The Open Group Base Specifications Issue 7, Chapter 12.1 Utility Argument Syntax". The Open Group. 2008. Archived from the original on 2013-04-30. Retrieved 2013-04-07. – Linux Conventions and Miscellany Manual (NB. Conventions for describing commands on Unix-like operating systems.)
- ^ "Command shell overview". Windows Server 2003 Product Help. Microsoft. 2005-01-21. Archived from the original on 2012-07-12. Retrieved 2013-04-07.
- ^ "Command-Line Syntax Key". Windows Server 2008 R2 TechNet Library. Microsoft. 2010-01-25. Archived from the original on 2013-05-04. Retrieved 2013-04-07.
- ^ Kernighan, Brian W.; Pike, Rob (1984). The UNIX Programming Environment. Englewood Cliffs: Prentice-Hall. ISBN 0-13-937699-2.
- ^ Pouzin, Louis. "The Origin of the Shell". Multicians.org. Archived from the original on 2017-12-21. Retrieved 2013-09-22.
- ^ Wilcox, Joe (2010-08-24). "Remembering Windows 95's launch 15 years later". BetaNews. Archived from the original on 2015-02-18. Retrieved 2015-02-18.
- ^ "A history of Windows". windows.microsoft.com. Archived from the original on 2015-03-01.
- ^ "master - platform/external/mksh - Git at Google". android.googlesource.com. Archived from the original on 2016-01-21. Retrieved 2018-03-18.
- ^ "Android adb shell - ash or ksh?". stackoverflow.com. Archived from the original on 2017-07-02. Retrieved 2018-03-14.
- ^ "Android sh source". GitHub. Archived from the original on 2012-12-17.
- ^ "Android toolbox source". GitHub.
- ^ "Windows POSIX shell compatibility". 2013-02-22. Archived from the original on 2017-07-03. Retrieved 2017-08-26.
- ^ openharmony/third_party_toybox, OpenHarmony, 2021-10-14, retrieved 2024-07-07
- ^ "调测 - Shell介绍 - 《华为鸿蒙操作系统(OpenHarmony) v1.0 开发者文档》 - 书栈网 · BookStack". www.bookstack.cn. Retrieved 2024-07-07.
- ^ "Configuration Fundamentals Configuration Guide, Cisco IOS Release 15M&T". Cisco. 2013-10-30. Using the Command-Line Interface. Archived from the original on 2016-11-18. Retrieved 2016-11-28.
The Cisco IOS command-line interface (CLI) is the primary user interface…
- ^ "Command-Line Interface Overview". www.juniper.net. Archived from the original on 2003-09-08. Retrieved 2018-03-14.
- ^ "Google strange goodness". Archived from the original on 2014-03-04. Retrieved 2014-02-27.
- ^ "jQuery Terminal Emulator". Archived from the original on 2021-04-20. Retrieved 2021-04-20.
- ^ "DuckDuckGo TTY". Archived from the original on 2021-05-07. Retrieved 2021-04-20.
External links
[edit]- The Roots of DOS David Hunter, Softalk for the IBM Personal Computer March 1983. Archived at Patersontech.com since 2000.
- Windows Commands: Microsoft TechNet Database "Command-Line Reference"
Command-line interface
View on GrokipediaOverview and Comparison
Definition and Core Concepts
A command-line interface (CLI) is a type of human-computer interface that relies exclusively on textual lines of input to issue commands to a computer program or operating system, with output also presented in text form, typically accessed through a terminal emulator or console window.[5] This interaction occurs via a command interpreter, often called a shell, which processes each line of text as a discrete instruction.[6] Unlike interfaces that employ visual elements, a CLI uses only characters displayed on the screen, eschewing icons, windows, or graphical metaphors.[7] At its core, a CLI operates on principles of textual input and output, where users enter commands using a keyboard and receive responses as plain text streams.[5] Commands are processed sequentially, with the shell interpreting and executing them one at a time upon submission, usually by pressing the Enter key, enabling a linear workflow without parallel visual navigation.[8] This design emphasizes keyboard-driven interaction, making it independent of pointing devices like mice and suited to environments where graphical rendering is unavailable or inefficient.[7] The primary purposes of CLIs include providing efficiency for experienced users through precise, scriptable commands that outperform graphical alternatives in speed and control for complex tasks.[5] They facilitate automation via scripting languages, allowing repetitive operations to be batched and executed without manual intervention.[9] Additionally, CLIs enable remote access to systems over networks, such as via SSH, and thrive in resource-constrained settings like servers or embedded devices where graphical interfaces would consume excessive memory and processing power.[8] A basic example of CLI interaction involves entering the commandls in Unix-like systems, which instructs the shell to list the contents of the current directory; upon execution, the terminal immediately displays a textual enumeration of files and folders, demonstrating the direct, instantaneous feedback loop.[7]
Comparison to Graphical User Interfaces
Command-line interfaces (CLIs) and graphical user interfaces (GUIs) represent two fundamental paradigms for human-computer interaction, with CLIs emphasizing text-based commands for direct system control and GUIs focusing on visual metaphors like windows, icons, menus, and pointers (WIMP) to facilitate intuitive navigation. This distinction arises from their design philosophies: CLIs require users to input precise textual instructions, enabling fine-grained manipulation of system resources, whereas GUIs abstract complexity through point-and-click interactions, prioritizing discoverability over explicit control. CLIs offer several advantages over GUIs, particularly in efficiency and resource management. For repetitive or complex tasks, such as batch processing files or configuring network settings, CLIs enable faster execution by allowing users to chain commands without navigating menus, often reducing interaction time by orders of magnitude in scripted workflows. They also consume fewer system resources, as they avoid rendering graphics and animations, making them ideal for low-power devices or environments with limited bandwidth. Additionally, CLIs excel in scripting and automation, where commands can be saved, modified, and executed programmatically, facilitating integration with tools like cron jobs or remote sessions via protocols such as SSH. Despite these strengths, CLIs present notable disadvantages compared to GUIs, especially for accessibility and user experience. The reliance on memorized syntax imposes a steeper learning curve, deterring novices who must learn specific commands and parameters without visual cues, unlike GUIs that provide self-evident options through icons and tooltips. Errors in CLI input, such as typos in command arguments, can lead to unintended outcomes without immediate visual feedback, increasing the risk of misconfigurations in critical operations. In practice, CLIs are predominantly used in scenarios demanding precision and scalability, such as server administration, software development environments (e.g., compiling code via terminals), and embedded systems where GUIs are impractical due to hardware constraints. Conversely, GUIs prevail in consumer-oriented desktops and laptops, where ease of use supports everyday tasks like web browsing or document editing. Modern operating systems often integrate both paradigms in hybrid models; for instance, Windows provides the PowerShell CLI for advanced scripting alongside the graphical Start menu for routine interactions, allowing users to leverage CLI efficiency within a GUI ecosystem.Types of Command-Line Interfaces
Operating System Command-Line Interfaces
Operating system command-line interfaces, commonly known as shells, are command interpreters that serve as the primary text-based mechanism for users to interact with the operating system, enabling direct access to system resources, file and directory management, and process control.[10] These interfaces interpret user-entered commands, execute corresponding programs or scripts, and manage the execution environment to facilitate efficient system administration.[11] Unlike application-specific CLIs, OS shells are deeply integrated with system utilities, providing foundational tools for tasks such as launching processes, monitoring system status, and configuring hardware interactions. In Unix-like operating systems, including Linux distributions and macOS, prominent examples include the Bourne-Again SHell (Bash) and the Z Shell (Zsh). Bash, developed by the GNU Project as a POSIX-compliant extension of the original Bourne shell, acts as the default interactive shell in many Linux environments, where it executes binaries by searching the system's PATH directory list and supports scripting for automated system tasks.[10] Zsh, an advanced interactive shell with features like improved autocompletion and themeable prompts, has been the default shell in macOS since version 10.15 (Catalina), enhancing user productivity in file navigation and command history management.[12][13] On Windows, the Command Prompt (cmd.exe) offers a basic shell for executing system utilities and batch files, while PowerShell provides a more robust, object-oriented alternative designed for cross-platform automation and .NET integration.[14][11] macOS accesses these Unix shells through the Terminal application, which bridges the CLI with the graphical desktop for seamless OS interaction.[13] Core functions of OS shells encompass executing binary executables and scripts, managing environment variables to customize the runtime context—such as settingPATH to locate commands or HOME for user directories—and employing pipes and redirection to manipulate data streams efficiently.[10] Pipes connect the standard output of one command to the standard input of another, allowing command chaining; for instance, in Bash or Zsh, the command ls -l | grep "file" generates a detailed directory listing and filters it to show only entries matching "file".[15] Redirection operators further enable saving output to files or reading input from them, as in ls > dirlist.txt to redirect the listing to a file or cat < input.txt to display file contents.[16] PowerShell supports similar piping with object passing for richer data handling, exemplified by Get-ChildItem | Where-Object { $_.Name -like "*file*" }, which filters directory items akin to Unix grep.[11]
Platform-specific conventions highlight differences in file system navigation within these shells. Unix-like systems, including those in macOS Terminal, utilize forward slashes (/) as path separators to denote hierarchical structures, such as /usr/bin for system binaries or /home/user for personal directories.[10] Windows shells, conversely, incorporate drive letters (e.g., C:, D:) to identify volumes and backslashes () as the directory separator, resulting in paths like C:\Users\Documents for user files or D:\Program Files for installed applications.[17] These features ensure compatibility with each OS's file system while allowing shells to perform cross-platform tasks when ported, such as Bash on Windows via subsystems.[10]
Application Command-Line Interfaces
Application command-line interfaces (CLIs) provide text-based mechanisms for users to interact with specific software applications or utilities, distinct from broader operating system shells, by executing domain-focused commands to control program behavior. These interfaces rely on typed instructions entered in a terminal, often initiated from an OS shell, to perform tasks like data manipulation, system configuration, or resource management within the application's scope. For instance, they enable direct invocation of tools without graphical intermediaries, supporting precise operations on external services or utilities.[18][5] Common examples illustrate their role in specialized workflows. Git, a distributed version control system, uses commands such asgit clone <url> to replicate remote repositories and git commit -m "message" to save local changes, all executed via the command line from a shell.[19][20] Docker's CLI manages containerized environments with instructions like docker run -it --name test busybox sh to launch interactive sessions, leveraging shell environment variables for configuration.[21] Curl serves as a versatile data transfer utility, supporting commands like curl -X POST -d "data" https://example.com to send HTTP requests with custom payloads.[22] Package managers exemplify this further: npm installs Node.js dependencies via npm install <package>, resolving and integrating modules into projects, while Debian's apt handles software deployment through apt install <package>, automatically managing dependencies.[23][24]
These CLIs employ domain-specific syntax optimized for their applications, such as Git's verb-noun structure (e.g., git add, git push) or curl's protocol-agnostic options for transfers across HTTP, FTP, and more, ensuring concise expression of complex operations. Integration with the OS shell allows seamless chaining, where outputs from one command pipe into another— for example, combining curl with text processors to filter responses—enhancing workflow efficiency without leaving the terminal environment.[25][26]
The primary benefits include precision in tool invocation, achieved through granular flags that target exact functionalities, such as Docker's --rm to auto-remove containers post-execution, reducing manual cleanup. Extensibility via arguments further supports customization, like curl's -H "Authorization: token" for authenticated requests, enabling adaptable scripting for automation across diverse scenarios while minimizing resource overhead compared to graphical alternatives.[27][22][21]
Historical Development
Early Command-Line Interfaces
The origins of command-line interfaces trace back to the 1950s, when mainframe computers like the IBM 701 relied on batch processing systems. These early setups used punched cards, magnetic tapes, and teletype terminals—electromechanical devices originally developed for telegraphy in the early 1900s—to submit jobs offline, with operators feeding instructions into the system for sequential execution without real-time interaction.[28][29] This non-interactive approach minimized human error in high-speed data processing but limited direct user control, as jobs could take hours or days to process.[28] A pivotal shift occurred in the 1960s with the advent of time-sharing systems, enabling interactive command-line interfaces. The Compatible Time-Sharing System (CTSS), developed at MIT starting in 1961 on the IBM 709 and later the 7094, introduced one of the first true CLIs, allowing multiple users to interact via remote terminals like Flexowriters and teletypes at speeds up to 110 baud.[30] Key features included crude line editing for input correction and the QED editor by Ken Thompson, which supported line-oriented operations and regular expression searches, though without advanced graphical elements or full-screen displays.[30] Building on this, Multics—jointly developed from 1965 by MIT, Bell Labs, and General Electric—advanced interactive CLIs with a shell that executed PL/I commands from dial-up terminals, integrating file system access, paging, and segmentation for multiprogramming by 1968.[31] The debut of Unix in 1971 marked another milestone, with Ken Thompson's shell on the PDP-11 minicomputer providing a foundational interactive CLI. Implemented in assembly language with 24K bytes of memory, it supported basic utilities for file manipulation, I/O redirection (e.g., < and >), and simple editing via character erase and line-kill sequences, but lacked command history recall or scripting.[32] As Unix evolved on the PDP-11 from its PDP-7 roots in 1969, the shell gained features like pipes in 1973 for command chaining, emphasizing text processing efficiency without visual interfaces.[33] In the mid-1970s, command-line interfaces extended to microcomputers through systems like CP/M, developed by Gary Kildall in 1974 for the Intel 8080 processor. Its Console Command Processor (CCP) offered a text-based CLI with built-in commands for file operations (e.g., save, erase, list) and transient program loading, portable across hardware via a modular BIOS, influencing early personal computing on over 200 microcomputer models by 1980.[34] These early CLIs prioritized textual, line-by-line interaction and basic recall mechanisms, laying the groundwork for efficient system control in resource-constrained environments.[30][32]Modern Evolution and Standardization
In the 1980s and 1990s, the evolution of command-line interfaces emphasized standardization to enhance portability across Unix-like systems. The Bourne shell, originally developed in 1977, became the de facto standard during this period, with its features formalized through the POSIX (Portable Operating System Interface) initiative. The IEEE 1003.2 standard for shell and utilities, ratified in September 1992, defined shell semantics primarily based on the System V variant of the Bourne shell, establishing a common command language, scripting syntax, and utility interfaces.[35] This standardization addressed fragmentation in early Unix variants by specifying behaviors for core commands, environment variables, and process control, enabling developers to write portable scripts.[36] A significant advancement was the Korn shell (ksh), released in 1983 by David Korn at Bell Labs, which integrated features from the Bourne and C shells, including improved scripting, command-line editing, and job control, influencing POSIX compliance and later shells.[37] Key implementations emerged to support this standardization. The GNU Project released Bash (Bourne Again SHell) in June 1989 as a free, POSIX-compatible extension of the Bourne shell, incorporating interactive features like command history and job control while maintaining backward compatibility.[38] In parallel, Microsoft introduced the Command Prompt with Windows NT 3.1 in July 1993, providing a text-based interface for the new 32-bit operating system that supported batch scripting and integration with MS-DOS tools, though it diverged from Unix conventions.[39] Entering the 2000s, command-line interfaces advanced with more sophisticated features for productivity and data handling. Microsoft launched Windows PowerShell 1.0 in November 2006, pioneering object-oriented piping that passes .NET objects between commands rather than text streams, allowing for richer data manipulation, error handling, and integration with Windows management tasks.[40] Similarly, Zsh underwent notable enhancements, with version 4.0 released in June 2001 introducing a mature, programmable completion system that expanded tab completion to include contextual suggestions for commands, options, filenames, and even remote filesystems, surpassing the capabilities of earlier shells.[41] The POSIX shell specifications, evolving from the 1988 IEEE 1003.1 base through subsequent revisions, have shaped the core of modern operating systems. Linux distributions, such as those based on the Linux kernel since 1991, default to POSIX-compliant shells like Bash, ensuring consistent behavior for system administration and scripting across environments.[42] macOS has similarly adhered to these standards; certified as UNIX 03-compliant in 2007, it used Bash as its default shell until 2019 (when it switched to Zsh), leveraging POSIX for command portability and developer tools.[42] Recent trends through 2025 reflect a push toward cross-platform compatibility and modern data paradigms in command-line interfaces. Nushell, first released in August 2019, exemplifies this by adopting a structured data model where command outputs are treated as tables, lists, or records—similar to PowerShell but with simpler syntax—enabling seamless querying, filtering, and piping across Linux, macOS, and Windows without text parsing ambiguities.[43] This approach addresses limitations in traditional text-based pipelines, supporting diverse data sources like JSON, CSV, and databases in a platform-agnostic manner.Anatomy of Command-Line Interfaces
Command Prompt and Input Mechanics
The command prompt serves as the primary visual indicator in a command-line interface (CLI), signaling the location for user input and often conveying contextual information such as the current working directory or user privileges. In Unix-like systems, particularly those employing the Bash shell, the default primary prompt string (PS1) is set to\s-\v\$, which displays the shell name (e.g., "bash") followed by its version and a trailing symbol—typically a dollar sign () for non-root users or a hash (#) for the root user—to denote privilege level.[](https://www.gnu.org/software/bash/manual/bash.html#Controlling-the-Prompt) This structure can be extended to include elements like the username (`\u`), hostname (`\h`), or current directory (`\w`) for enhanced usability. In contrast, the Windows Command Prompt (cmd.exe) uses a default prompt of `p$g, rendering the current drive letter, path, and a greater-than sign (>), as in C:\Users\Example>`, to indicate the file system location.[44]
Input mechanics in CLIs rely on terminal handling to capture and process keystrokes efficiently. As users type at the prompt, the terminal echoes each character to the screen, providing immediate visual feedback unless explicitly disabled. In Unix systems, input operates in canonical mode by default, where characters are line-buffered: they accumulate in a buffer until the Enter (newline) key is pressed, at which point the complete line is submitted to the shell for interpretation, allowing for editing with backspace or line-kill sequences.[45] Special keys like Ctrl+C trigger the INTR character, generating a SIGINT signal to interrupt the foreground process if the ISIG flag is enabled.[45] Similarly, in Windows, the console input buffer operates in processed mode, supporting line input where keystrokes are buffered and echoed until Enter submits the line, while Ctrl+C is intercepted as a signal (not passed as input) to terminate the running command.[46][47]
Terminal emulators play a crucial role in rendering the command prompt and managing input display within graphical environments. On Unix-like systems, xterm emulates legacy hardware terminals like the DEC VT102, providing escape sequences for cursor control, text formatting, and prompt rendering to ensure compatibility with CLI applications. This emulation allows the prompt and echoed input to appear consistently across diverse hardware. In Windows, the modern Windows Terminal emulator supports multiple shell profiles (including cmd.exe) in tabbed interfaces, handling ANSI escape codes and virtual terminal sequences to accurately display prompts, colors, and input without native console limitations.
CLI sessions incorporate resource protection through operating system-level process isolation, ensuring each interactive shell runs as an independent process with its own address space and permissions. In Unix, this model confines a shell session's access to system resources, preventing interference with other processes via memory separation and privilege checks enforced by the kernel.[48] Windows achieves similar isolation for cmd.exe instances, where each session operates within bounded memory and file handles, blocking unauthorized cross-access to mitigate security risks like privilege escalation. This design inherently safeguards shared resources, such as the file system or network, from compromise in one session affecting others.
Arguments, Options, and Syntax
In command-line interfaces, arguments are parameters passed to a command to specify its behavior or inputs. Positional arguments occupy fixed positions in the command line and are interpreted based on their order relative to the command name; for example, in thecp command, the first positional argument denotes the source file and the second the destination file, as in cp source dest.[49] Named options, in contrast, are explicitly identified and can appear in any order after the command, providing flexibility; a common example is the -v option for verbose output in many utilities, which enables detailed logging without altering positional parameters.[49]
Command-line options typically follow established conventions to ensure portability and usability. Short options consist of a single hyphen followed by a single alphanumeric character, such as -l for listing files in directory commands, and can be bundled together like -la to combine multiple options efficiently.[49] Long options, popularized in GNU utilities, use a double hyphen followed by a descriptive word, such as --list, offering greater readability and allowing equivalents to short forms; these are parsed using libraries like GNU getopt_long, which supports both formats while adhering to POSIX guidelines for option placement before operands unless terminated by --.[50] The POSIX standard mandates that options precede operands and recommends the -- sequence to signal the end of options, treating subsequent arguments as positional regardless of form.[49]
Syntax rules in command-line interfaces rely on whitespace as the primary delimiter to separate tokens, with unquoted spaces or tabs dividing arguments into distinct units.[51] To include spaces within an argument, such as a filename like "file name", double or single quotes enclose the entire value, preserving the internal whitespace as literal; double quotes allow variable expansions while single quotes treat all content literally.[51] Escaping special characters, including shell metacharacters like *, ?, or $, uses a backslash (\) immediately before the character to remove its special meaning, as in echo file\ name or ls file\*.txt, ensuring the shell passes the exact sequence to the command.[51]
Command usage is formally described in documentation through standardized formats. In manual pages (man pages), the SYNOPSIS section employs a concise notation where square brackets [] denote optional elements, ellipses ... indicate repeatable arguments, vertical bars | separate alternatives, and italics or placeholders specify replaceable values, such as cp [OPTION]... SOURCE DEST to outline the structure.[52] Similarly, the --help output, a GNU convention, mirrors this syntax in plain text, providing a quick reference like Usage: ls [OPTION]... [FILE]... to summarize valid combinations without full prose details.[50]
Command-Line Interpreters
Functionality and Internal Operations
The command-line interpreter, often referred to as a shell, begins processing user input through a parser that tokenizes the command line into words and operators. Tokenization occurs by scanning the input stream and applying rules to identify boundaries based on whitespace, quotes, and metacharacters such as|, >, or <, without performing substitutions at this stage.[51] For instance, unquoted spaces separate tokens, while quoted strings preserve embedded spaces as part of a single token.[53] Following tokenization, the parser handles expansions, including parameter expansion for variables like $PATH or ${variable}, which substitutes the parameter's value into the command line.[51] Pathname expansion, or globbing, then replaces wildcard patterns such as * (matching any string of characters) or ? (matching a single character) with sorted lists of matching filenames, provided the noglob option is not set.[54]
Once expansions are complete, the interpreter constructs an execution pipeline for the command. For simple commands, it first checks if the command name matches a built-in function, such as cd for changing directories or echo for outputting text, which executes directly within the shell's process without creating a new one.[51] If no match is found and the name lacks slashes, it searches the directories in $PATH for an external executable; upon locating one, the shell forks a child process using system calls like fork() and overlays the new program image via execve(), allowing the external binary to run independently.[55] I/O redirection operators, such as > filename for output or < inputfile for input, modify file descriptors in the executing environment before or after forking, directing streams to files or devices.[56] Pipelines, connected by |, chain multiple commands by forking subshells for each segment, where the standard output of one becomes the input of the next, enabling data flow without intermediate files.[51]
Error handling in command-line interpreters relies on exit status codes returned by executed commands, standardized as 0 for successful completion and any non-zero value (typically 1–255) to indicate failure, such as command not found (127) or permission denied (126).[51] The shell captures these codes via wait() after forking and stores the last command's status in the $? variable for scripting or further processing; in pipelines, the exit status defaults to that of the last command unless options like pipefail alter this behavior.[57]
Role as Operating System Shells
A command-line interface interpreter, commonly known as a shell, serves as an interactive or non-interactive environment that interprets user commands and facilitates communication with the operating system kernel. In interactive mode, it accepts input from the user via a terminal and executes corresponding system calls, while in non-interactive mode, it processes commands from scripts or batch files without user intervention. This role positions the shell as a critical intermediary layer, enabling both human users and automated processes to access kernel services securely and efficiently.[58][59] Shells integrate deeply into operating system startup and session management processes. During Unix-like system login, the login daemon authenticates the user and invokes the default shell, often /bin/sh, as specified in the /etc/passwd file, initiating an interactive session that inherits the environment variables from the parent process. This inheritance ensures that child processes launched by the shell receive a copy of variables like PATH and HOME, maintaining consistency across the session. Such integration allows the shell to manage environment setup, including sourcing profile scripts like /etc/profile for system-wide configurations.[60][61][62] In modern Linux distributions, Bash functions as the default shell, providing robust command interpretation and scripting capabilities for user interactions and system administration. For instance, Bash integrates with systemd, the prevalent init system, where service unit files often use Bash scripts in ExecStart directives to automate service launches and management tasks, such as restarting daemons or handling dependencies. This synergy enhances operational efficiency in environments like servers and desktops.[63] Security features in shells enforce operating system-level user permissions, preventing unauthorized access to resources by running commands under the invoking user's privileges. Specialized variants, such as the restricted Bash shell (rbash), implement sandboxing by limiting path changes, command execution outside the PATH, and variable modifications, thereby creating controlled environments for untrusted users or kiosks. These mechanisms rely on underlying Unix permission models to isolate and constrain activities without altering core kernel behaviors.[64]Usage and Implementation
Basic Command Execution
Basic command execution in a command-line interface begins when the user types a command at the shell prompt and presses Enter, prompting the shell to process the input. The shell first tokenizes and parses the input into a simple command structure, performing necessary expansions such as parameter substitution before handling redirections if specified. For commands without slashes in their names, the shell searches for the executable by first checking special built-ins likecd, then user-defined functions, and finally scanning directories listed in the PATH environment variable to locate a matching executable file. Upon finding the command, the shell executes it, typically by forking a child process and using system calls like execve to replace the process image with the command's program; the shell then waits for completion and collects the exit status, which indicates success (0) or failure (non-zero). In Unix-like systems, this process adheres to POSIX standards for command search and execution. Similarly, in Windows Command Prompt (cmd.exe), the interpreter searches the %PATH% environment variable for executables when a full path is not provided, executing them via CreateProcess and displaying results in the console.
The output from executed commands is directed to standard output (stdout, file descriptor 1) as text streams, with errors routed to standard error (stderr, file descriptor 2) by default, allowing separation for logging or redirection. These streams are displayed directly in the terminal unless piped or redirected; for lengthy outputs, pagination tools like more can be used to view content page-by-page, pausing after each screenful and responding to user input such as spacebar to advance or 'q' to quit. In POSIX-compliant systems, more reads from stdin or files and writes to stdout in this manner. Windows cmd supports a similar more command for pagination, often used as command | more.
Simple examples illustrate everyday command execution. The ls command in Unix-like shells lists directory contents, displaying filenames and optionally metadata like permissions and sizes when invoked as ls -l; its output streams to stdout for review. The cd utility changes the current working directory, such as cd /home/user to navigate to a user's home folder, updating the shell's environment without producing output unless an error occurs. For testing output, echo writes its arguments to stdout followed by a newline, e.g., echo "Hello, world!" produces the string on the next line. In Windows, equivalents include dir for listing files and directories (e.g., dir shows volume info and contents), cd for directory changes (e.g., cd C:\Users), and echo for string output (e.g., echo Hello, world!).
Common pitfalls during execution include "command not found" errors, which occur with exit status 127 when the shell fails to locate the executable in PATH or as a built-in, resolvable by verifying the PATH variable (e.g., via echo $PATH), installing missing software, or using the full path to the command. Permission errors, such as "permission denied," arise when attempting to execute a file lacking execute permissions (e.g., via chmod +x file to fix) or access restricted directories, often requiring elevated privileges with tools like sudo in Unix-like systems or running cmd as administrator in Windows. These issues highlight the importance of proper environment setup and access rights for successful command invocation.
Built-in Help and Error Handling
Command-line interfaces incorporate built-in help systems to facilitate user interaction and learning. A prevalent mechanism is the--help flag, standardized in GNU utilities, which outputs a concise usage summary including available options, arguments, and basic syntax before exiting with a success status of 0.[65] For instance, executing git --help displays a synopsis of Git's subcommands and options, aiding quick reference without invoking the full manual.[66] Complementing this, the man command retrieves formatted manual pages from the system's reference documentation, structured into sections like 1 for executable programs and 8 for system administration commands; invocation follows man [section] topic, such as man 1 ls to view details on the ls utility.[67]
Errors in command execution fall into distinct categories, primarily syntax errors from malformed input and runtime failures during processing. Syntax errors arise from invalid options or arguments, triggering immediate diagnostic messages to standard error (stderr); for example, ls -z yields "ls: invalid option -- 'z'" and exits with a non-zero status.[51] Runtime errors occur when commands attempt operations on unavailable resources, such as cat nonexistent.txt reporting "cat: nonexistent.txt: No such file or directory" via stderr, often with exit codes like 1 for general failure or 127 if the command is not found.[51] These diagnostics provide contextual clues, including the offending input and suggested corrections where possible.
Handling errors involves inspecting exit statuses and capturing output for review. In POSIX-compliant shells, the special variable $? captures the exit code of the most recent foreground command, where 0 denotes success and values from 1 to 255 indicate specific failures, enabling conditional logic like if [ $? -ne 0 ]; then echo "Command failed"; fi.[51] For persistent logging, the tee utility reads from standard input and duplicates it to both stdout and one or more files, supporting options like -a to append rather than overwrite; however, in pipelines (e.g., command 2>&1 | tee log.txt), the overall exit status reflects the last process unless configured otherwise via --output-error modes.[68]
Modern terminals enhance error visibility through colorized output, improving accessibility by distinguishing normal results from issues. The ls command, for example, employs --color=auto to apply ANSI escape codes for file types when connected to a terminal, with executable files in green and directories in blue, while many utilities route error messages to stderr in red for immediate highlighting; environment variables like LS_COLORS allow customization to meet user preferences for contrast and readability.[69]
Scripting Capabilities
Scripting capabilities in command-line interfaces vary by operating system and shell, enabling task automation through sequences of commands stored in text files executed non-interactively. In Unix-like systems, this is achieved via shell scripts interpreted by shells like Bash or sh. In Windows, equivalents include batch files (.bat or .cmd) for the Command Prompt (cmd.exe) and more advanced scripts (.ps1) for PowerShell, which supports object-oriented automation.[70] These approaches allow repeatable operations, with Unix shells providing a foundational model that influenced cross-platform tools.Fundamentals of Shell Scripting
Shell scripting in Unix-like systems enables the automation of tasks by storing sequences of commands in text files, which the command-line interpreter executes non-interactively, bypassing the usual interactive prompt.[51] These scripts leverage the shell's ability to process commands from files, allowing for repeatable operations without manual input each time.[71] Unlike interactive sessions, script execution reads the entire file upfront, expands variables and substitutions, and runs commands in sequence until completion or error.[72] In Windows Command Prompt, batch files use similar principles but with distinct syntax; for example, variables are set asSET VAR=value and referenced with %VAR%, conditionals via IF statements (e.g., IF EXIST file.txt ECHO File found), and loops with FOR (e.g., FOR %%i IN (1 2 3) DO ECHO %%i). Batch files are executed by invoking their name in cmd.exe or double-clicking, without a shebang equivalent. PowerShell scripts, while more powerful, begin with .ps1 files and require setting an execution policy (e.g., Set-ExecutionPolicy RemoteSigned) for security; basic variables use $VAR = value, conditionals if ($condition) { ... }, and loops foreach ($item in $list) { ... }, run via .\script.ps1.[73]
A key feature of Unix shell scripts is the shebang line, placed at the beginning of the file as #! followed by the path to the desired interpreter, such as #!/bin/sh for a POSIX-compliant shell or #!/bin/bash for the GNU Bash shell.[71] This directive instructs the operating system to invoke the specified interpreter to process the script, ensuring compatibility across environments.[74] Scripts are saved with extensions like .sh for clarity, though this is conventional rather than required.[75]
Basic elements of shell scripting include variables, conditionals, and loops, which build structured logic on top of simple command execution. Variables are assigned using the syntax VAR=value without spaces around the equals sign, creating local parameters accessible via $VAR or ${VAR} for expansion in commands.[76] Conditionals use the if construct to evaluate conditions, such as if test-condition; then commands; fi, where test-condition often employs the [ builtin to check file existence, string equality, or numeric comparisons, executing the following block only if the condition yields a zero exit status.[77] Loops, like the for construct, iterate over lists with syntax for VAR in word1 word2 ...; do commands; done, sequentially assigning each word to VAR and running the commands for each iteration.[78]
To execute a Unix script, it must first be made runnable by setting execute permissions on the file using the chmod command, typically chmod +x script.sh, which adds the execute bit for the owner, group, or others as needed. Once permissions are set, the script can be invoked directly with ./script.sh from its directory, assuming the shebang is present and the interpreter is in the system's PATH; alternatively, it can be run explicitly via the interpreter like sh script.sh.[75] This process mirrors basic command execution but applies it to the entire file contents non-interactively.[72] In Windows, batch files require no special permissions and run directly; PowerShell scripts may need policy adjustments for execution.
A representative example is a simple backup script in Bash that copies a file with a timestamp to avoid overwrites:
#!/bin/bash
DATE=$(date +%Y-%m-%d)
cp important_file.txt backups/important_file_$DATE.txt
echo "Backup of important_file.txt completed on $DATE."
#!/bin/bash
DATE=$(date +%Y-%m-%d)
cp important_file.txt backups/important_file_$DATE.txt
echo "Backup of important_file.txt completed on $DATE."
date command generates a formatted timestamp stored in the DATE variable, cp performs the copy operation to a backups directory, and echo provides feedback; the script assumes the backups directory exists and uses command substitution $( ) for dynamic output integration. After saving this as backup.sh, apply chmod +x backup.sh and run ./backup.sh to create a dated copy, demonstrating how scripting combines familiar commands for automation.[79] For comparison, a Windows batch equivalent might be:
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
copy important_file.txt backups\important_file_%YY%-%MM%-%DD%.txt
echo Backup of important_file.txt completed on %YY%-%MM%-%DD%.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
copy important_file.txt backups\important_file_%YY%-%MM%-%DD%.txt
echo Backup of important_file.txt completed on %YY%-%MM%-%DD%.
wmic for date and copy for the operation, run as backup.bat.
Advanced Automation and Integration
Advanced shell scripting extends basic capabilities through constructs like functions, which encapsulate reusable code blocks for modular programming. In Bash, functions are defined using the syntaxname() { commands; } and can accept arguments similar to scripts, enabling the organization of complex tasks into manageable units. Arrays provide dynamic storage for multiple values, declared as declare -a array_name or simply array=(value1 value2), allowing indexed access and manipulation essential for handling lists or datasets in automation. Signal handling via the trap builtin intercepts interrupts like SIGINT or SIGTERM, executing custom actions such as cleanup routines before exit, which is crucial for robust scripts in production environments.[80] Here documents facilitate multi-line input to commands, using <<EOF delimiters to embed structured data directly in scripts without temporary files.
In PowerShell, advanced features include functions (function Name { ... }), arrays ($array = @('value1', 'value2')), and error handling with try/catch blocks, offering object pipelines for integration (e.g., $data | Where-Object { $_ -gt 10 }). Batch files support limited functions via CALL and subroutines with GOTO.[70]
Integration with external systems enhances CLI automation, such as invoking RESTful APIs through curl within Unix scripts to fetch or post data programmatically. For instance, a script might use curl -X GET https://api.example.com/data to retrieve JSON responses, which can then be parsed for further processing. In Windows, PowerShell uses Invoke-RestMethod for similar API calls, returning structured objects. Scheduling is achieved via cron jobs in Unix, where scripts are registered in crontab files using formats like * * * * * /path/to/script.sh to run at specified intervals, automating periodic tasks like backups or monitoring.[81] Windows equivalents include Task Scheduler for PowerShell or batch scripts. Complex workflows leverage piping to chain commands, where output from one process becomes input to the next, enabling efficient data transformation across multiple tools without intermediate storage; PowerShell extends this with object piping.
Practical examples illustrate these features in deployment scenarios, such as a Unix script that clones a Git repository via git clone over SSH, applies configurations using functions and arrays for environment variables, and handles signals to ensure safe rollbacks. Data processing pipelines often combine here documents with piping, for example, feeding SQL queries into psql and piping results through awk for aggregation, streamlining ETL operations. Tools like awk and sed integrate seamlessly for text manipulation; awk processes structured data with pattern-action rules, such as awk '{sum += $1} END {print sum}' to compute totals, while sed performs stream editing like substitutions via s/old/new/g. In Windows, PowerShell cmdlets like Select-Object and ForEach-Object provide analogous functionality. These elements collectively enable scalable, integrated automation in CLI environments across platforms.
Extensions and Variations
Text User Interfaces
Text user interfaces (TUIs), also known as text-based user interfaces, are a type of interface that operates within a terminal environment, utilizing text characters to create structured, interactive displays rather than graphical elements. These interfaces leverage libraries such as ncurses to manage terminal capabilities, enabling the development of full-screen applications that go beyond simple command-line input. Ncurses, a free software emulation of the System V Release 4.0 curses library, provides functions for controlling cursor movement, drawing windows, and handling input in a terminal-independent manner.[82][83] Key features of TUIs include keyboard-driven navigation, where users interact via key bindings to move between elements, select options, and perform actions, often mimicking menu systems or forms. They support the creation of multiple overlapping windows within the text mode display, allowing for organized layouts such as side-by-side panels or dialog boxes constructed from ASCII characters. Additionally, some TUIs incorporate mouse support when the underlying terminal emulator permits it, enabling point-and-click interactions alongside keyboard controls. These capabilities are facilitated by ncurses routines that handle screen updates efficiently, buffering changes to minimize flicker and optimize performance in resource-constrained environments.[84][82] Prominent examples of TUIs include the htop process viewer, which uses ncurses to present a dynamic, scrollable table of system processes with real-time updates and interactive sorting.[85] The Midnight Commander file manager employs ncurses (or the alternative S-Lang library) to offer a dual-pane interface for browsing, copying, and editing files via keyboard shortcuts and optional mouse input.[86] Similarly, the mutt email client relies on ncurses for its threaded message views, attachment handling, and configurable key mappings, providing a compact yet powerful text-based email experience.[87] The Vim text editor also utilizes ncurses for terminal control in its console mode, enabling modal editing with highlighted syntax and multi-window splits.[88] TUIs build upon the foundational command-line interface by integrating directly with shell environments, where users can launch these applications from a prompt and return to command execution upon exit, thus blending direct text input with more visual, structured layouts to enhance usability without requiring graphical hardware.[83]Contemporary Applications and Tools
In the realm of cloud computing, command-line interfaces have become essential for managing infrastructure as code (IaC), enabling declarative provisioning and automation of resources. The AWS CLI, released in 2013, provides a unified toolset for interacting with Amazon Web Services, supporting scripting for tasks like resource deployment and configuration management.[89] Similarly, the Azure CLI facilitates IaC practices by allowing users to define, deploy, and update Azure resources through scripts and extensions, integrating seamlessly with tools like Bicep and Terraform for reproducible environments.[90][91] Modern CLI tools post-2010 emphasize usability enhancements and performance. tldr, introduced in 2013, offers simplified, example-based help pages as a community-driven alternative to verbose man pages, fetching concise guides for common commands via a lightweight client.[92] fzf, a fuzzy finder developed in 2015, enables interactive searching across files, history, or outputs, integrating with shells like Bash and Zsh to streamline navigation and selection in terminal workflows.[93] AI-assisted extensions, such as the GitHub Copilot CLI launched in public preview in 2025, allow natural language queries in the terminal for code generation, debugging, and project exploration, powered by large language models.[94][95] Cross-platform developments leverage modern languages for efficiency and portability. Ripgrep, a Rust-based search tool released in 2016, outperforms traditional grep in speed and respects .gitignore rules by default, making it ideal for large codebases across operating systems.[96] WebAssembly (Wasm) CLIs, emerging prominently in the 2020s, enable sandboxed execution of tools like Wasmtime's CLI for running Wasm modules with system access via WASI, or wasm-tools for parsing and optimizing binaries, facilitating secure, polyglot command-line applications.[97][98] Recent trends in CLIs focus on accessibility and security to broaden adoption. Voice-to-text integrations, such as the Azure Speech CLI introduced in recent updates, convert spoken input to commands in real-time, aiding users with motor impairments or hands-free scenarios.[99] Security enhancements incorporate zero-trust principles, where tools like cloud CLIs enforce continuous authentication and least-privilege access, as highlighted in industry analyses of CLI protections against unauthorized resource manipulation.[100]References
- https://en.wikibooks.org/wiki/Bash_Shell_Scripting/History
