Какой язык используется в командной строке windows

From Wikipedia, the free encyclopedia

From Wikipedia, the free encyclopedia

For other uses, see CMD.

«Command Prompt» redirects here. For the concept, see Command prompt.

Command Prompt (cmd.exe)

Command prompt icon (windows).png
Other names Windows Command Processor
Developer(s) Microsoft, IBM, ReactOS contributors
Initial release December 1987; 35 years ago
Stable release

10.0.22000.282

Operating system
  • Windows NT family
  • Windows CE family
  • OS/2
  • eComStation
  • ArcaOS
  • ReactOS
Platform IA-32, x86-64, ARM (and historically DEC Alpha, MIPS, PowerPC, and Itanium)
Predecessor COMMAND.COM
Type Command-line interpreter

Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2,[1] eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS[2] operating systems. On Windows CE .NET 4.2,[3] Windows CE 5.0[4] and Windows Embedded CE 6.0[5] it is referred to as the Command Processor Shell. Its implementations differ between operating systems, but the behavior and basic set of commands are consistent. cmd.exe is the counterpart of COMMAND.COM in DOS and Windows 9x systems, and analogous to the Unix shells used on Unix-like systems. The initial version of cmd.exe for Windows NT was developed by Therese Stowell.[6] Windows CE 2.11 was the first embedded Windows release to support a console and a Windows CE version of cmd.exe.[7] The ReactOS implementation of cmd.exe is derived from FreeCOM, the FreeDOS command line interpreter.[2]

Operation[edit]

cmd.exe interacts with the user through a command-line interface. On Windows, this interface is implemented through the Win32 console. cmd.exe may take advantage of features available to native programs of its own platform. For example, on OS/2 and Windows, it can use real pipes in command pipelines, allowing both sides of the pipeline to run concurrently. As a result, it is possible to redirect the standard error stream. (COMMAND.COM uses temporary files, and runs the two sides serially, one after the other.)

Multiple commands can be processed in a single command line using the command separator &&.[8]

When using this separator in the Windows cmd.exe, each command must complete successfully for the following commands to execute. For example:

C:>CommandA && CommandB && CommandC

In the above example, Command B will only execute if Command A completes successfully, and the execution of Command C depends on the successful completion of Command B. To process subsequent commands even if the previous command produces an error, the command separator & should be used.[9] For example:

C:>CommandA & CommandB & CommandC

On Windows XP or later, the maximum length of the string that can be used at the command prompt is 8191 characters. On earlier versions, such as Windows 2000 or Windows NT 4.0, the maximum length of the string is 2047 characters. This limit includes the command line, individual environment variables that are inherited by other processes, and all environment variable expansions.[10]

Quotation marks are required for the following special characters:[8]

& < > [ ] { } ^ = ; ! ' + , ` ~ [white space]

Internal commands[edit]

OS/2[edit]

The following is a list of the Microsoft OS/2 internal cmd.exe commands:[11]

  • break
  • chcp
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • detach
  • dir
  • dpath
  • echo
  • erase
  • exit
  • for
  • goto
  • if
  • md
  • mkdir
  • path
  • pause
  • prompt
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • type
  • ver
  • verify
  • vol

Windows NT family[edit]

The following list of internal commands is supported by cmd.exe on Windows NT and later:[12]

  • assoc
  • break
  • call
  • cd
  • chdir
  • cls
  • color
  • copy
  • date
  • del
  • dir
  • dpath
  • echo
  • endlocal
  • erase
  • exit
  • for
  • ftype
  • goto
  • if
  • keys
  • md
  • mkdir
  • mklink (introduced in Windows Vista)
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • setlocal
  • shift
  • start
  • time
  • title
  • type
  • ver
  • verify
  • vol

Windows CE[edit]

The following list of commands is supported by cmd.exe on Windows CE .NET 4.2,[13] Windows CE 5.0[14] and Windows Embedded CE 6.0:[15]

  • attrib
  • call
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • dir
  • echo
  • erase
  • exit
  • goto
  • help
  • if
  • md
  • mkdir
  • move
  • path
  • pause
  • prompt
  • pwd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • title
  • type

In addition, the net command is available as an external command stored in Windowsnet.exe.

ReactOS[edit]

Command Prompt (cmd.exe) on ReactOS

The ReactOS implementation includes the following internal commands:[2]

  • ?
  • alias
  • assoc
  • beep
  • call
  • cd
  • chdir
  • choice
  • cls
  • color
  • copy
  • ctty
  • date
  • del
  • delete
  • delay
  • dir
  • dirs
  • echo
  • echos
  • echoerr
  • echoserr
  • endlocal
  • erase
  • exit
  • for
  • free
  • goto
  • history
  • if
  • memory
  • md
  • mkdir
  • mklink
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rmdir
  • rem
  • ren
  • rename
  • replace
  • screen
  • set
  • setlocal
  • shift
  • start
  • time
  • timer
  • title
  • type
  • ver
  • verify
  • vol

Comparison with COMMAND.COM[edit]

On Windows, cmd.exe is mostly compatible with COMMAND.COM but provides the following extensions over it:

  • More detailed error messages than the blanket «Bad command or file name» (in the case of malformed commands) of COMMAND.COM. In OS/2, errors are reported in the chosen language of the system, their text being taken from the system message files. The HELP command can then be issued with the error message number to obtain further information.
  • Supports using of arrow keys to scroll through command history. (Under DOS this function was only available under DR DOS (through HISTORY) and later via an external component called DOSKEY.)
  • Adds rotating command-line completion for file and folder paths, where the user can cycle through results for the prefix using the Tab ↹, and ⇧ Shift+Tab ↹ for reverse direction.
  • Treats the caret character (^) as the escape character; the character following it is to be taken literally. There are special characters in cmd.exe and COMMAND.COM (e.g. «<«, «>» and «|») that are meant to alter the behavior of the command line processor. The caret character forces the command line processor to interpret them literally.
  • Supports delayed variable expansion with SETLOCAL EnableDelayedExpansion, allowing values of variables to be calculated at runtime instead of during parsing of script before execution (Windows 2000 and later), fixing DOS idioms that made using control structures hard and complex.[16] The extensions can be disabled, providing a stricter compatibility mode.

Internal commands have also been improved:

  • The DELTREE command was merged into the RD command, as part of its /S switch.
  • SetLocal and EndLocal commands limit the scope of changes to the environment. Changes made to the command line environment after SetLocal commands are local to the batch file. EndLocal command restores the previous settings.[17]
  • The Call command allows subroutines within batch file. The Call command in COMMAND.COM only supports calling external batch files.
  • File name parser extensions to the Set command are comparable with C shell.[further explanation needed]
  • The Set command can perform expression evaluation.
  • An expansion of the For command supports parsing files and arbitrary sets in addition to file names.
  • The new PushD and PopD commands provide access past navigated paths similar to «forward» and «back» buttons in a web browser or File Explorer.
  • The conditional IF command can perform case-insensitive comparisons and numeric equality and inequality comparisons in addition to case-sensitive string comparisons. (This was available in DR-DOS, but not in PC DOS or MS-DOS.)

See also[edit]

  • Comparison of command shells
  • List of DOS commands
  • COMMAND.COM
  • PowerShell
  • Windows Terminal

References[edit]

  1. ^ «Notes on using the default OS/2 command processor (CMD.EXE)». www.tavi.co.uk.
  2. ^ a b c «reactos/reactos». GitHub. 4 December 2021.
  3. ^ «Command Processor Shell (Windows CE .NET 4.2)». docs.microsoft.com.
  4. ^ «Command Processor Shell (Windows CE 5.0)». docs.microsoft.com.
  5. ^ «Command Processor Shell (Windows Embedded CE 6.0)». docs.microsoft.com.
  6. ^ Zachary, G. Pascal (1994). Showstopper! The Breakneck Race to Create Windows NT and the Next Generation at Microsoft. The Free Press. ISBN 0-02-935671-7.
  7. ^ Douglas McConnaughey Boling (2001). Programming Microsoft Windows CE (2nd ed.). Microsoft Press. ISBN 978-0735614437.
  8. ^ a b «cmd». docs.microsoft.com.
  9. ^ «Command Redirection, Pipes — Windows CMD — SS64.com». ss64.com. Retrieved 2021-09-23.
  10. ^ Command prompt (Cmd.exe) command-line string limitation
  11. ^ Microsoft Operating System/2 User’s Reference (PDF). Microsoft. 1987.
  12. ^ Hill, Tim (1998). Windows NT Shell Scripting. Macmillan Technical Publishing. ISBN 978-1578700479.
  13. ^ «Command Processor Commands (Windows CE .NET 4.2)». docs.microsoft.com.
  14. ^ «Command Processor Commands (Windows CE 5.0)». docs.microsoft.com.
  15. ^ «Command Processor Commands (Windows Embedded CE 6.0)». docs.microsoft.com.
  16. ^ «Windows 2000 delayed environment variable expansion». Windows IT Pro. Archived from the original on 2015-07-13. Retrieved 2015-07-13.
  17. ^ «Setlocal». TechNet. Microsoft. Retrieved 2015-01-13.

Further reading[edit]

  • David Moskowitz; David Kerr (1994). OS/2 2.11 Unleashed (2nd ed.). Sams Publishing. ISBN 978-0672304453.
  • Stanek, William R. (2008). Windows Command-Line Administrator’s Pocket Consultant (2nd ed.). Microsoft Press. ISBN 978-0735622623.

External links[edit]

  • «Command-line reference A-Z». Microsoft.{{cite web}}: CS1 maint: url-status (link)
  • «Cmd». Microsoft Windows XP Product Documentation. Microsoft. Archived from the original on 2011-09-02. Retrieved 2006-05-24.
  • «Command Prompt: frequently asked questions». windows Help. Microsoft. Archived from the original on 2015-04-22. Retrieved 2015-04-20.
  • «An A–Z Index of the Windows CMD command line». SS64.com.
  • «Windows CMD.com – Hub of Windows Commands». windowscmd.com.

From Wikipedia, the free encyclopedia

For other uses, see CMD.

«Command Prompt» redirects here. For the concept, see Command prompt.

Command Prompt (cmd.exe)

Command prompt icon (windows).png
Other names Windows Command Processor
Developer(s) Microsoft, IBM, ReactOS contributors
Initial release December 1987; 35 years ago
Stable release

10.0.22000.282

Operating system
  • Windows NT family
  • Windows CE family
  • OS/2
  • eComStation
  • ArcaOS
  • ReactOS
Platform IA-32, x86-64, ARM (and historically DEC Alpha, MIPS, PowerPC, and Itanium)
Predecessor COMMAND.COM
Type Command-line interpreter

Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2,[1] eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS[2] operating systems. On Windows CE .NET 4.2,[3] Windows CE 5.0[4] and Windows Embedded CE 6.0[5] it is referred to as the Command Processor Shell. Its implementations differ between operating systems, but the behavior and basic set of commands are consistent. cmd.exe is the counterpart of COMMAND.COM in DOS and Windows 9x systems, and analogous to the Unix shells used on Unix-like systems. The initial version of cmd.exe for Windows NT was developed by Therese Stowell.[6] Windows CE 2.11 was the first embedded Windows release to support a console and a Windows CE version of cmd.exe.[7] The ReactOS implementation of cmd.exe is derived from FreeCOM, the FreeDOS command line interpreter.[2]

Operation[edit]

cmd.exe interacts with the user through a command-line interface. On Windows, this interface is implemented through the Win32 console. cmd.exe may take advantage of features available to native programs of its own platform. For example, on OS/2 and Windows, it can use real pipes in command pipelines, allowing both sides of the pipeline to run concurrently. As a result, it is possible to redirect the standard error stream. (COMMAND.COM uses temporary files, and runs the two sides serially, one after the other.)

Multiple commands can be processed in a single command line using the command separator &&.[8]

When using this separator in the Windows cmd.exe, each command must complete successfully for the following commands to execute. For example:

C:>CommandA && CommandB && CommandC

In the above example, Command B will only execute if Command A completes successfully, and the execution of Command C depends on the successful completion of Command B. To process subsequent commands even if the previous command produces an error, the command separator & should be used.[9] For example:

C:>CommandA & CommandB & CommandC

On Windows XP or later, the maximum length of the string that can be used at the command prompt is 8191 characters. On earlier versions, such as Windows 2000 or Windows NT 4.0, the maximum length of the string is 2047 characters. This limit includes the command line, individual environment variables that are inherited by other processes, and all environment variable expansions.[10]

Quotation marks are required for the following special characters:[8]

& < > [ ] { } ^ = ; ! ' + , ` ~ [white space]

Internal commands[edit]

OS/2[edit]

The following is a list of the Microsoft OS/2 internal cmd.exe commands:[11]

  • break
  • chcp
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • detach
  • dir
  • dpath
  • echo
  • erase
  • exit
  • for
  • goto
  • if
  • md
  • mkdir
  • path
  • pause
  • prompt
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • type
  • ver
  • verify
  • vol

Windows NT family[edit]

The following list of internal commands is supported by cmd.exe on Windows NT and later:[12]

  • assoc
  • break
  • call
  • cd
  • chdir
  • cls
  • color
  • copy
  • date
  • del
  • dir
  • dpath
  • echo
  • endlocal
  • erase
  • exit
  • for
  • ftype
  • goto
  • if
  • keys
  • md
  • mkdir
  • mklink (introduced in Windows Vista)
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • setlocal
  • shift
  • start
  • time
  • title
  • type
  • ver
  • verify
  • vol

Windows CE[edit]

The following list of commands is supported by cmd.exe on Windows CE .NET 4.2,[13] Windows CE 5.0[14] and Windows Embedded CE 6.0:[15]

  • attrib
  • call
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • dir
  • echo
  • erase
  • exit
  • goto
  • help
  • if
  • md
  • mkdir
  • move
  • path
  • pause
  • prompt
  • pwd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • title
  • type

In addition, the net command is available as an external command stored in Windowsnet.exe.

ReactOS[edit]

Command Prompt (cmd.exe) on ReactOS

The ReactOS implementation includes the following internal commands:[2]

  • ?
  • alias
  • assoc
  • beep
  • call
  • cd
  • chdir
  • choice
  • cls
  • color
  • copy
  • ctty
  • date
  • del
  • delete
  • delay
  • dir
  • dirs
  • echo
  • echos
  • echoerr
  • echoserr
  • endlocal
  • erase
  • exit
  • for
  • free
  • goto
  • history
  • if
  • memory
  • md
  • mkdir
  • mklink
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rmdir
  • rem
  • ren
  • rename
  • replace
  • screen
  • set
  • setlocal
  • shift
  • start
  • time
  • timer
  • title
  • type
  • ver
  • verify
  • vol

Comparison with COMMAND.COM[edit]

On Windows, cmd.exe is mostly compatible with COMMAND.COM but provides the following extensions over it:

  • More detailed error messages than the blanket «Bad command or file name» (in the case of malformed commands) of COMMAND.COM. In OS/2, errors are reported in the chosen language of the system, their text being taken from the system message files. The HELP command can then be issued with the error message number to obtain further information.
  • Supports using of arrow keys to scroll through command history. (Under DOS this function was only available under DR DOS (through HISTORY) and later via an external component called DOSKEY.)
  • Adds rotating command-line completion for file and folder paths, where the user can cycle through results for the prefix using the Tab ↹, and ⇧ Shift+Tab ↹ for reverse direction.
  • Treats the caret character (^) as the escape character; the character following it is to be taken literally. There are special characters in cmd.exe and COMMAND.COM (e.g. «<«, «>» and «|») that are meant to alter the behavior of the command line processor. The caret character forces the command line processor to interpret them literally.
  • Supports delayed variable expansion with SETLOCAL EnableDelayedExpansion, allowing values of variables to be calculated at runtime instead of during parsing of script before execution (Windows 2000 and later), fixing DOS idioms that made using control structures hard and complex.[16] The extensions can be disabled, providing a stricter compatibility mode.

Internal commands have also been improved:

  • The DELTREE command was merged into the RD command, as part of its /S switch.
  • SetLocal and EndLocal commands limit the scope of changes to the environment. Changes made to the command line environment after SetLocal commands are local to the batch file. EndLocal command restores the previous settings.[17]
  • The Call command allows subroutines within batch file. The Call command in COMMAND.COM only supports calling external batch files.
  • File name parser extensions to the Set command are comparable with C shell.[further explanation needed]
  • The Set command can perform expression evaluation.
  • An expansion of the For command supports parsing files and arbitrary sets in addition to file names.
  • The new PushD and PopD commands provide access past navigated paths similar to «forward» and «back» buttons in a web browser or File Explorer.
  • The conditional IF command can perform case-insensitive comparisons and numeric equality and inequality comparisons in addition to case-sensitive string comparisons. (This was available in DR-DOS, but not in PC DOS or MS-DOS.)

See also[edit]

  • Comparison of command shells
  • List of DOS commands
  • COMMAND.COM
  • PowerShell
  • Windows Terminal

References[edit]

  1. ^ «Notes on using the default OS/2 command processor (CMD.EXE)». www.tavi.co.uk.
  2. ^ a b c «reactos/reactos». GitHub. 4 December 2021.
  3. ^ «Command Processor Shell (Windows CE .NET 4.2)». docs.microsoft.com.
  4. ^ «Command Processor Shell (Windows CE 5.0)». docs.microsoft.com.
  5. ^ «Command Processor Shell (Windows Embedded CE 6.0)». docs.microsoft.com.
  6. ^ Zachary, G. Pascal (1994). Showstopper! The Breakneck Race to Create Windows NT and the Next Generation at Microsoft. The Free Press. ISBN 0-02-935671-7.
  7. ^ Douglas McConnaughey Boling (2001). Programming Microsoft Windows CE (2nd ed.). Microsoft Press. ISBN 978-0735614437.
  8. ^ a b «cmd». docs.microsoft.com.
  9. ^ «Command Redirection, Pipes — Windows CMD — SS64.com». ss64.com. Retrieved 2021-09-23.
  10. ^ Command prompt (Cmd.exe) command-line string limitation
  11. ^ Microsoft Operating System/2 User’s Reference (PDF). Microsoft. 1987.
  12. ^ Hill, Tim (1998). Windows NT Shell Scripting. Macmillan Technical Publishing. ISBN 978-1578700479.
  13. ^ «Command Processor Commands (Windows CE .NET 4.2)». docs.microsoft.com.
  14. ^ «Command Processor Commands (Windows CE 5.0)». docs.microsoft.com.
  15. ^ «Command Processor Commands (Windows Embedded CE 6.0)». docs.microsoft.com.
  16. ^ «Windows 2000 delayed environment variable expansion». Windows IT Pro. Archived from the original on 2015-07-13. Retrieved 2015-07-13.
  17. ^ «Setlocal». TechNet. Microsoft. Retrieved 2015-01-13.

Further reading[edit]

  • David Moskowitz; David Kerr (1994). OS/2 2.11 Unleashed (2nd ed.). Sams Publishing. ISBN 978-0672304453.
  • Stanek, William R. (2008). Windows Command-Line Administrator’s Pocket Consultant (2nd ed.). Microsoft Press. ISBN 978-0735622623.

External links[edit]

  • «Command-line reference A-Z». Microsoft.{{cite web}}: CS1 maint: url-status (link)
  • «Cmd». Microsoft Windows XP Product Documentation. Microsoft. Archived from the original on 2011-09-02. Retrieved 2006-05-24.
  • «Command Prompt: frequently asked questions». windows Help. Microsoft. Archived from the original on 2015-04-22. Retrieved 2015-04-20.
  • «An A–Z Index of the Windows CMD command line». SS64.com.
  • «Windows CMD.com – Hub of Windows Commands». windowscmd.com.

From Wikipedia, the free encyclopedia

For other uses, see CMD.

«Command Prompt» redirects here. For the concept, see Command prompt.

Command Prompt (cmd.exe)

Command prompt icon (windows).png
Other names Windows Command Processor
Developer(s) Microsoft, IBM, ReactOS contributors
Initial release December 1987; 35 years ago
Stable release

10.0.22000.282

Operating system
  • Windows NT family
  • Windows CE family
  • OS/2
  • eComStation
  • ArcaOS
  • ReactOS
Platform IA-32, x86-64, ARM (and historically DEC Alpha, MIPS, PowerPC, and Itanium)
Predecessor COMMAND.COM
Type Command-line interpreter

Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2,[1] eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS[2] operating systems. On Windows CE .NET 4.2,[3] Windows CE 5.0[4] and Windows Embedded CE 6.0[5] it is referred to as the Command Processor Shell. Its implementations differ between operating systems, but the behavior and basic set of commands are consistent. cmd.exe is the counterpart of COMMAND.COM in DOS and Windows 9x systems, and analogous to the Unix shells used on Unix-like systems. The initial version of cmd.exe for Windows NT was developed by Therese Stowell.[6] Windows CE 2.11 was the first embedded Windows release to support a console and a Windows CE version of cmd.exe.[7] The ReactOS implementation of cmd.exe is derived from FreeCOM, the FreeDOS command line interpreter.[2]

Operation[edit]

cmd.exe interacts with the user through a command-line interface. On Windows, this interface is implemented through the Win32 console. cmd.exe may take advantage of features available to native programs of its own platform. For example, on OS/2 and Windows, it can use real pipes in command pipelines, allowing both sides of the pipeline to run concurrently. As a result, it is possible to redirect the standard error stream. (COMMAND.COM uses temporary files, and runs the two sides serially, one after the other.)

Multiple commands can be processed in a single command line using the command separator &&.[8]

When using this separator in the Windows cmd.exe, each command must complete successfully for the following commands to execute. For example:

C:>CommandA && CommandB && CommandC

In the above example, Command B will only execute if Command A completes successfully, and the execution of Command C depends on the successful completion of Command B. To process subsequent commands even if the previous command produces an error, the command separator & should be used.[9] For example:

C:>CommandA & CommandB & CommandC

On Windows XP or later, the maximum length of the string that can be used at the command prompt is 8191 characters. On earlier versions, such as Windows 2000 or Windows NT 4.0, the maximum length of the string is 2047 characters. This limit includes the command line, individual environment variables that are inherited by other processes, and all environment variable expansions.[10]

Quotation marks are required for the following special characters:[8]

& < > [ ] { } ^ = ; ! ' + , ` ~ [white space]

Internal commands[edit]

OS/2[edit]

The following is a list of the Microsoft OS/2 internal cmd.exe commands:[11]

  • break
  • chcp
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • detach
  • dir
  • dpath
  • echo
  • erase
  • exit
  • for
  • goto
  • if
  • md
  • mkdir
  • path
  • pause
  • prompt
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • type
  • ver
  • verify
  • vol

Windows NT family[edit]

The following list of internal commands is supported by cmd.exe on Windows NT and later:[12]

  • assoc
  • break
  • call
  • cd
  • chdir
  • cls
  • color
  • copy
  • date
  • del
  • dir
  • dpath
  • echo
  • endlocal
  • erase
  • exit
  • for
  • ftype
  • goto
  • if
  • keys
  • md
  • mkdir
  • mklink (introduced in Windows Vista)
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • setlocal
  • shift
  • start
  • time
  • title
  • type
  • ver
  • verify
  • vol

Windows CE[edit]

The following list of commands is supported by cmd.exe on Windows CE .NET 4.2,[13] Windows CE 5.0[14] and Windows Embedded CE 6.0:[15]

  • attrib
  • call
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • dir
  • echo
  • erase
  • exit
  • goto
  • help
  • if
  • md
  • mkdir
  • move
  • path
  • pause
  • prompt
  • pwd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • title
  • type

In addition, the net command is available as an external command stored in Windowsnet.exe.

ReactOS[edit]

Command Prompt (cmd.exe) on ReactOS

The ReactOS implementation includes the following internal commands:[2]

  • ?
  • alias
  • assoc
  • beep
  • call
  • cd
  • chdir
  • choice
  • cls
  • color
  • copy
  • ctty
  • date
  • del
  • delete
  • delay
  • dir
  • dirs
  • echo
  • echos
  • echoerr
  • echoserr
  • endlocal
  • erase
  • exit
  • for
  • free
  • goto
  • history
  • if
  • memory
  • md
  • mkdir
  • mklink
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rmdir
  • rem
  • ren
  • rename
  • replace
  • screen
  • set
  • setlocal
  • shift
  • start
  • time
  • timer
  • title
  • type
  • ver
  • verify
  • vol

Comparison with COMMAND.COM[edit]

On Windows, cmd.exe is mostly compatible with COMMAND.COM but provides the following extensions over it:

  • More detailed error messages than the blanket «Bad command or file name» (in the case of malformed commands) of COMMAND.COM. In OS/2, errors are reported in the chosen language of the system, their text being taken from the system message files. The HELP command can then be issued with the error message number to obtain further information.
  • Supports using of arrow keys to scroll through command history. (Under DOS this function was only available under DR DOS (through HISTORY) and later via an external component called DOSKEY.)
  • Adds rotating command-line completion for file and folder paths, where the user can cycle through results for the prefix using the Tab ↹, and ⇧ Shift+Tab ↹ for reverse direction.
  • Treats the caret character (^) as the escape character; the character following it is to be taken literally. There are special characters in cmd.exe and COMMAND.COM (e.g. «<«, «>» and «|») that are meant to alter the behavior of the command line processor. The caret character forces the command line processor to interpret them literally.
  • Supports delayed variable expansion with SETLOCAL EnableDelayedExpansion, allowing values of variables to be calculated at runtime instead of during parsing of script before execution (Windows 2000 and later), fixing DOS idioms that made using control structures hard and complex.[16] The extensions can be disabled, providing a stricter compatibility mode.

Internal commands have also been improved:

  • The DELTREE command was merged into the RD command, as part of its /S switch.
  • SetLocal and EndLocal commands limit the scope of changes to the environment. Changes made to the command line environment after SetLocal commands are local to the batch file. EndLocal command restores the previous settings.[17]
  • The Call command allows subroutines within batch file. The Call command in COMMAND.COM only supports calling external batch files.
  • File name parser extensions to the Set command are comparable with C shell.[further explanation needed]
  • The Set command can perform expression evaluation.
  • An expansion of the For command supports parsing files and arbitrary sets in addition to file names.
  • The new PushD and PopD commands provide access past navigated paths similar to «forward» and «back» buttons in a web browser or File Explorer.
  • The conditional IF command can perform case-insensitive comparisons and numeric equality and inequality comparisons in addition to case-sensitive string comparisons. (This was available in DR-DOS, but not in PC DOS or MS-DOS.)

See also[edit]

  • Comparison of command shells
  • List of DOS commands
  • COMMAND.COM
  • PowerShell
  • Windows Terminal

References[edit]

  1. ^ «Notes on using the default OS/2 command processor (CMD.EXE)». www.tavi.co.uk.
  2. ^ a b c «reactos/reactos». GitHub. 4 December 2021.
  3. ^ «Command Processor Shell (Windows CE .NET 4.2)». docs.microsoft.com.
  4. ^ «Command Processor Shell (Windows CE 5.0)». docs.microsoft.com.
  5. ^ «Command Processor Shell (Windows Embedded CE 6.0)». docs.microsoft.com.
  6. ^ Zachary, G. Pascal (1994). Showstopper! The Breakneck Race to Create Windows NT and the Next Generation at Microsoft. The Free Press. ISBN 0-02-935671-7.
  7. ^ Douglas McConnaughey Boling (2001). Programming Microsoft Windows CE (2nd ed.). Microsoft Press. ISBN 978-0735614437.
  8. ^ a b «cmd». docs.microsoft.com.
  9. ^ «Command Redirection, Pipes — Windows CMD — SS64.com». ss64.com. Retrieved 2021-09-23.
  10. ^ Command prompt (Cmd.exe) command-line string limitation
  11. ^ Microsoft Operating System/2 User’s Reference (PDF). Microsoft. 1987.
  12. ^ Hill, Tim (1998). Windows NT Shell Scripting. Macmillan Technical Publishing. ISBN 978-1578700479.
  13. ^ «Command Processor Commands (Windows CE .NET 4.2)». docs.microsoft.com.
  14. ^ «Command Processor Commands (Windows CE 5.0)». docs.microsoft.com.
  15. ^ «Command Processor Commands (Windows Embedded CE 6.0)». docs.microsoft.com.
  16. ^ «Windows 2000 delayed environment variable expansion». Windows IT Pro. Archived from the original on 2015-07-13. Retrieved 2015-07-13.
  17. ^ «Setlocal». TechNet. Microsoft. Retrieved 2015-01-13.

Further reading[edit]

  • David Moskowitz; David Kerr (1994). OS/2 2.11 Unleashed (2nd ed.). Sams Publishing. ISBN 978-0672304453.
  • Stanek, William R. (2008). Windows Command-Line Administrator’s Pocket Consultant (2nd ed.). Microsoft Press. ISBN 978-0735622623.

External links[edit]

  • «Command-line reference A-Z». Microsoft.{{cite web}}: CS1 maint: url-status (link)
  • «Cmd». Microsoft Windows XP Product Documentation. Microsoft. Archived from the original on 2011-09-02. Retrieved 2006-05-24.
  • «Command Prompt: frequently asked questions». windows Help. Microsoft. Archived from the original on 2015-04-22. Retrieved 2015-04-20.
  • «An A–Z Index of the Windows CMD command line». SS64.com.
  • «Windows CMD.com – Hub of Windows Commands». windowscmd.com.

From Wikipedia, the free encyclopedia

For other uses, see CMD.

«Command Prompt» redirects here. For the concept, see Command prompt.

Command Prompt (cmd.exe)

Command prompt icon (windows).png
Other names Windows Command Processor
Developer(s) Microsoft, IBM, ReactOS contributors
Initial release December 1987; 35 years ago
Stable release

10.0.22000.282

Operating system
  • Windows NT family
  • Windows CE family
  • OS/2
  • eComStation
  • ArcaOS
  • ReactOS
Platform IA-32, x86-64, ARM (and historically DEC Alpha, MIPS, PowerPC, and Itanium)
Predecessor COMMAND.COM
Type Command-line interpreter

Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2,[1] eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS[2] operating systems. On Windows CE .NET 4.2,[3] Windows CE 5.0[4] and Windows Embedded CE 6.0[5] it is referred to as the Command Processor Shell. Its implementations differ between operating systems, but the behavior and basic set of commands are consistent. cmd.exe is the counterpart of COMMAND.COM in DOS and Windows 9x systems, and analogous to the Unix shells used on Unix-like systems. The initial version of cmd.exe for Windows NT was developed by Therese Stowell.[6] Windows CE 2.11 was the first embedded Windows release to support a console and a Windows CE version of cmd.exe.[7] The ReactOS implementation of cmd.exe is derived from FreeCOM, the FreeDOS command line interpreter.[2]

Operation[edit]

cmd.exe interacts with the user through a command-line interface. On Windows, this interface is implemented through the Win32 console. cmd.exe may take advantage of features available to native programs of its own platform. For example, on OS/2 and Windows, it can use real pipes in command pipelines, allowing both sides of the pipeline to run concurrently. As a result, it is possible to redirect the standard error stream. (COMMAND.COM uses temporary files, and runs the two sides serially, one after the other.)

Multiple commands can be processed in a single command line using the command separator &&.[8]

When using this separator in the Windows cmd.exe, each command must complete successfully for the following commands to execute. For example:

C:>CommandA && CommandB && CommandC

In the above example, Command B will only execute if Command A completes successfully, and the execution of Command C depends on the successful completion of Command B. To process subsequent commands even if the previous command produces an error, the command separator & should be used.[9] For example:

C:>CommandA & CommandB & CommandC

On Windows XP or later, the maximum length of the string that can be used at the command prompt is 8191 characters. On earlier versions, such as Windows 2000 or Windows NT 4.0, the maximum length of the string is 2047 characters. This limit includes the command line, individual environment variables that are inherited by other processes, and all environment variable expansions.[10]

Quotation marks are required for the following special characters:[8]

& < > [ ] { } ^ = ; ! ' + , ` ~ [white space]

Internal commands[edit]

OS/2[edit]

The following is a list of the Microsoft OS/2 internal cmd.exe commands:[11]

  • break
  • chcp
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • detach
  • dir
  • dpath
  • echo
  • erase
  • exit
  • for
  • goto
  • if
  • md
  • mkdir
  • path
  • pause
  • prompt
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • type
  • ver
  • verify
  • vol

Windows NT family[edit]

The following list of internal commands is supported by cmd.exe on Windows NT and later:[12]

  • assoc
  • break
  • call
  • cd
  • chdir
  • cls
  • color
  • copy
  • date
  • del
  • dir
  • dpath
  • echo
  • endlocal
  • erase
  • exit
  • for
  • ftype
  • goto
  • if
  • keys
  • md
  • mkdir
  • mklink (introduced in Windows Vista)
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • setlocal
  • shift
  • start
  • time
  • title
  • type
  • ver
  • verify
  • vol

Windows CE[edit]

The following list of commands is supported by cmd.exe on Windows CE .NET 4.2,[13] Windows CE 5.0[14] and Windows Embedded CE 6.0:[15]

  • attrib
  • call
  • cd
  • chdir
  • cls
  • copy
  • date
  • del
  • dir
  • echo
  • erase
  • exit
  • goto
  • help
  • if
  • md
  • mkdir
  • move
  • path
  • pause
  • prompt
  • pwd
  • rd
  • rem
  • ren
  • rename
  • rmdir
  • set
  • shift
  • start
  • time
  • title
  • type

In addition, the net command is available as an external command stored in Windowsnet.exe.

ReactOS[edit]

Command Prompt (cmd.exe) on ReactOS

The ReactOS implementation includes the following internal commands:[2]

  • ?
  • alias
  • assoc
  • beep
  • call
  • cd
  • chdir
  • choice
  • cls
  • color
  • copy
  • ctty
  • date
  • del
  • delete
  • delay
  • dir
  • dirs
  • echo
  • echos
  • echoerr
  • echoserr
  • endlocal
  • erase
  • exit
  • for
  • free
  • goto
  • history
  • if
  • memory
  • md
  • mkdir
  • mklink
  • move
  • path
  • pause
  • popd
  • prompt
  • pushd
  • rd
  • rmdir
  • rem
  • ren
  • rename
  • replace
  • screen
  • set
  • setlocal
  • shift
  • start
  • time
  • timer
  • title
  • type
  • ver
  • verify
  • vol

Comparison with COMMAND.COM[edit]

On Windows, cmd.exe is mostly compatible with COMMAND.COM but provides the following extensions over it:

  • More detailed error messages than the blanket «Bad command or file name» (in the case of malformed commands) of COMMAND.COM. In OS/2, errors are reported in the chosen language of the system, their text being taken from the system message files. The HELP command can then be issued with the error message number to obtain further information.
  • Supports using of arrow keys to scroll through command history. (Under DOS this function was only available under DR DOS (through HISTORY) and later via an external component called DOSKEY.)
  • Adds rotating command-line completion for file and folder paths, where the user can cycle through results for the prefix using the Tab ↹, and ⇧ Shift+Tab ↹ for reverse direction.
  • Treats the caret character (^) as the escape character; the character following it is to be taken literally. There are special characters in cmd.exe and COMMAND.COM (e.g. «<«, «>» and «|») that are meant to alter the behavior of the command line processor. The caret character forces the command line processor to interpret them literally.
  • Supports delayed variable expansion with SETLOCAL EnableDelayedExpansion, allowing values of variables to be calculated at runtime instead of during parsing of script before execution (Windows 2000 and later), fixing DOS idioms that made using control structures hard and complex.[16] The extensions can be disabled, providing a stricter compatibility mode.

Internal commands have also been improved:

  • The DELTREE command was merged into the RD command, as part of its /S switch.
  • SetLocal and EndLocal commands limit the scope of changes to the environment. Changes made to the command line environment after SetLocal commands are local to the batch file. EndLocal command restores the previous settings.[17]
  • The Call command allows subroutines within batch file. The Call command in COMMAND.COM only supports calling external batch files.
  • File name parser extensions to the Set command are comparable with C shell.[further explanation needed]
  • The Set command can perform expression evaluation.
  • An expansion of the For command supports parsing files and arbitrary sets in addition to file names.
  • The new PushD and PopD commands provide access past navigated paths similar to «forward» and «back» buttons in a web browser or File Explorer.
  • The conditional IF command can perform case-insensitive comparisons and numeric equality and inequality comparisons in addition to case-sensitive string comparisons. (This was available in DR-DOS, but not in PC DOS or MS-DOS.)

See also[edit]

  • Comparison of command shells
  • List of DOS commands
  • COMMAND.COM
  • PowerShell
  • Windows Terminal

References[edit]

  1. ^ «Notes on using the default OS/2 command processor (CMD.EXE)». www.tavi.co.uk.
  2. ^ a b c «reactos/reactos». GitHub. 4 December 2021.
  3. ^ «Command Processor Shell (Windows CE .NET 4.2)». docs.microsoft.com.
  4. ^ «Command Processor Shell (Windows CE 5.0)». docs.microsoft.com.
  5. ^ «Command Processor Shell (Windows Embedded CE 6.0)». docs.microsoft.com.
  6. ^ Zachary, G. Pascal (1994). Showstopper! The Breakneck Race to Create Windows NT and the Next Generation at Microsoft. The Free Press. ISBN 0-02-935671-7.
  7. ^ Douglas McConnaughey Boling (2001). Programming Microsoft Windows CE (2nd ed.). Microsoft Press. ISBN 978-0735614437.
  8. ^ a b «cmd». docs.microsoft.com.
  9. ^ «Command Redirection, Pipes — Windows CMD — SS64.com». ss64.com. Retrieved 2021-09-23.
  10. ^ Command prompt (Cmd.exe) command-line string limitation
  11. ^ Microsoft Operating System/2 User’s Reference (PDF). Microsoft. 1987.
  12. ^ Hill, Tim (1998). Windows NT Shell Scripting. Macmillan Technical Publishing. ISBN 978-1578700479.
  13. ^ «Command Processor Commands (Windows CE .NET 4.2)». docs.microsoft.com.
  14. ^ «Command Processor Commands (Windows CE 5.0)». docs.microsoft.com.
  15. ^ «Command Processor Commands (Windows Embedded CE 6.0)». docs.microsoft.com.
  16. ^ «Windows 2000 delayed environment variable expansion». Windows IT Pro. Archived from the original on 2015-07-13. Retrieved 2015-07-13.
  17. ^ «Setlocal». TechNet. Microsoft. Retrieved 2015-01-13.

Further reading[edit]

  • David Moskowitz; David Kerr (1994). OS/2 2.11 Unleashed (2nd ed.). Sams Publishing. ISBN 978-0672304453.
  • Stanek, William R. (2008). Windows Command-Line Administrator’s Pocket Consultant (2nd ed.). Microsoft Press. ISBN 978-0735622623.

External links[edit]

  • «Command-line reference A-Z». Microsoft.{{cite web}}: CS1 maint: url-status (link)
  • «Cmd». Microsoft Windows XP Product Documentation. Microsoft. Archived from the original on 2011-09-02. Retrieved 2006-05-24.
  • «Command Prompt: frequently asked questions». windows Help. Microsoft. Archived from the original on 2015-04-22. Retrieved 2015-04-20.
  • «An A–Z Index of the Windows CMD command line». SS64.com.
  • «Windows CMD.com – Hub of Windows Commands». windowscmd.com.

Аннотация: Описываются возможности языка командных файлов: работа с переменными и параметрами командной строки, реализация циклов, условных операторов и операторов перехода. Даются примеры обработки текстовых файлов с помощью командных файлов

Язык интерпретатора Cmd.exe. Командные файлы

Язык оболочки командной строки (shell language) в Windows реализован в виде командных (или пакетных) файлов. Командный файл в Windows — это обычный текстовый файл с расширением bat или cmd, в котором записаны допустимые команды операционной системы (как внешние, так и внутренние), а также некоторые дополнительные инструкции и ключевые слова, придающие командным файлам некоторое сходство с алгоритмическими языками программирования. Например, если записать в файл deltmp.bat следующие команды:

C:
CD %TEMP%
DEL /F *.tmp

и запустить его на выполнение (аналогично исполняемым файлам с расширением com или exe), то мы удалим все файлы во временной директории Windows. Таким образом, исполнение командного файла приводит к тому же результату, что и последовательный ввод записанных в нем команд. При этом не проводится никакой предварительной компиляции или проверки синтаксиса кода; если встречается строка с ошибочной командой, то она игнорируется. Очевидно, что если вам приходится часто выполнять одни и те же действия, то использование командных файлов может сэкономить много времени.

Вывод сообщений и дублирование команд

По умолчанию команды пакетного файла перед исполнением выводятся на экран, что выглядит не очень эстетично. С помощью команды ECHO OFF можно отключить дублирование команд, идущих после нее (сама команда ECHO OFF при этом все же дублируется). Например,

REM Следующие две команды будут дублироваться на экране …
DIR C:
ECHO OFF
REM А остальные уже не будут
DIR D:

Для восстановления режима дублирования используется команда ECHO ON. Кроме этого, можно отключить дублирование любой отдельной строки в командном файле, написав в начале этой строки символ @, например:

ECHO ON
REM Команда DIR C: дублируется на экране
DIR C:
REM А команда DIR D: — нет
@DIR D:

Таким образом, если поставить в самое начало файла команду

то это решит все проблемы с дублированием команд.

В пакетном файле можно выводить на экран строки с сообщениями. Делается это с помощью команды

Например,

Команда ECHO. (точка должна следовать
непосредственно за словом «ECHO»)
выводит на экран пустую строку. Например,

@ECHO OFF
ECHO Привет!
ECHO.
ECHO Пока!

Часто бывает удобно для просмотра сообщений, выводимых из пакетного файла, предварительно полностью очистить экран командой CLS.

Используя механизм перенаправления ввода/вывода (символы > и >>), можно направить сообщения, выводимые командой ECHO, в определенный текстовый файл. Например:

@ECHO OFF
ECHO Привет! > hi.txt
ECHO Пока! >> hi.txt

С помощью такого метода можно, скажем,
заполнять файлы-протоколы с отчетом о
произведенных действиях. Например:

@ECHO OFF
REM Попытка копирования
XCOPY C:PROGRAMS D:PROGRAMS /s
REM Добавление сообщения в файл report.txt в случае
REM удачного завершения копирования
IF NOT ERRORLEVEL 1 ECHO Успешное копирование >> report.txt

Использование параметров командной строки

При запуске пакетных файлов в командной строке можно указывать произвольное число параметров, значения которых можно использовать внутри файла. Это позволяет, например, применять один и тот же командный файл для выполнения команд с различными параметрами.

Для доступа из командного файла к параметрам командной строки применяются символы %0, %1, …, %9 или %*. При этом вместо %0 подставляется имя выполняемого пакетного файла, вместо %1, %2, …, %9 — значения первых девяти параметров командной строки соответственно, а вместо %* — все аргументы. Если в командной строке при вызове пакетного файла задано меньше девяти параметров, то «лишние» переменные из %1 – %9 замещаются пустыми строками. Рассмотрим следующий пример. Пусть имеется командный файл copier.bat следующего содержания:

@ECHO OFF
CLS
ECHO Файл %0 копирует каталог %1 в %2
XCOPY %1 %2 /S

Если запустить его из командной строки с двумя параметрами, например

copier.bat C:Programs D:Backup

то на экран выведется сообщение

Файл copier.bat копирует каталог C:Programs в D:Backup

и произойдет копирование каталога C:Programs со всеми его подкаталогами в D:Backup.

При необходимости можно использовать более девяти параметров командной строки. Это достигается с помощью команды SHIFT, которая изменяет значения замещаемых параметров с %0 по %9, копируя каждый параметр в предыдущий, то есть значение %1 копируется в %0, значение %2 – в %1 и т.д. Замещаемому параметру %9 присваивается значение параметра, следующего в командной строке за старым значением %9. Если же такой параметр не задан, то новое значение %9 — пустая строка.

Рассмотрим пример. Пусть командный файл my.bat вызван из командной строки следующим образом:

Тогда %0=my.bat, %1=p1, %2=p2, %3=p3, параметры %4 – %9 являются пустыми строками. После выполнения команды SHIFT значения замещаемых параметров изменятся следующим образом: %0=p1, %1=p2, %2=p3, параметры %3 – %9 – пустые строки.

При включении расширенной обработки команд SHIFT поддерживает ключ /n, задающий начало сдвига параметров с номера n, где n может быть числом от 0 до 9.

Например, в следующей команде:

параметр %2 заменяется на %3, %3 на %4 и т.д., а параметры %0 и %1 остаются без изменений.

Команда, обратная SHIFT (обратный сдвиг), отсутствует. После выполнения SHIFT уже нельзя восстановить параметр (%0), который был первым перед сдвигом. Если в командной строке задано больше десяти параметров, то команду SHIFT можно использовать несколько раз.

В командных файлах имеются некоторые возможности синтаксического анализа заменяемых параметров. Для параметра с номером n (%n) допустимы синтаксические конструкции (операторы), представленные в табл. 3.1.

Таблица
3.1.
Операторы для заменяемых параметров

Операторы Описание
%~Fn Переменная %n расширяется до полного имени файла
%~Dn Из переменной %n выделяется только имя диска
%~Pn Из переменной %n выделяется только путь к файлу
%~Nn Из переменной %n выделяется только имя файла
%~Xn Из переменной %n выделяется расширение имени файла
%~Sn Значение операторов N и X для переменной %n изменяется так, что они работают с кратким именем файла
%~$PATH:n Проводится поиск по каталогам, заданным в переменной среды PATH, и переменная %n заменяется на полное имя первого найденного файла. Если переменная PATH не определена или в результате поиска не найден ни один файл, эта конструкция заменяется на пустую строку. Естественно, здесь переменную PATH можно заменить на любое другое допустимое значение

Данные синтаксические конструкции можно объединять друг с другом, например:

%~DPn — из переменной %n выделяется имя диска и путь,

%~NXn — из переменной %n выделяется имя файла и расширение.

Рассмотрим следующий пример. Пусть мы находимся в каталоге C:TEXT и запускаем пакетный файл с параметром Рассказ.doc ( %1=Рассказ.doc ). Тогда применение операторов, описанных в табл. 3.1, к параметру %1 даст следующие результаты:

%~F1=C:TEXTРассказ.doc
%~D1=C:
%~P1=TEXT
%~N1=Рассказ
%~X1=.doc
%~DP1=C:TEXT
%~NX1=Рассказ.doc

Предисловие от автора, Рича Тёрнера из Microsoft. Это статья о командной строке: от её появления и эволюции до планов капитального ремонта Windows Console и командной строки в будущих версиях Windows. Будь вы опытным профессионалом или новичком в IT, надеемся, что вы найдёте статью интересной.

Давным-давно в далёкой-далёкой серверной…

С первых дней развития информатики людям нужен был эффективный способ передавать компьютеру команды и данные и видеть результат выполнения этих команд/вычислений.

Одним из первых по-настоящему эффективных человеко-машинных интерфейсов стал Tele-Typewriter или «телетайп». Это электромеханическая машина с клавиатурой для ввода данных и каким-нибудь устройством вывода — сначала использовался принтер, позже экран.

Вводимые оператором символы локально буферизуются и отправляются с телетайпа на соседний компьютер или мейнфрейм в виде серии сигналов по электрическому кабелю (например, RS-232) со скоростью 10 символов в секунду (110 бод, бит в секунду, bps):


Телетайп Model 33 ASR

Примечание: Дэвид Гессвейн ведёт отличный сайт по PDP-8, где можно найти больше информации об ASR33 (и соответствующей технологии PDP-8), в том числе фотографии, видео и др.

Программа на компьютере получает введённые символы, решает, что с ними делать, и, возможно, асинхронно отправляет ответ на телетайп. Телетайп может напечатать/показать оператору полученные символы.

Затем технология улучшилась, скорость передачи выросла до 19200 bps, а шумные и дорогие принтеры заменили ЭЛТ-дисплеями (широко распространённый тип дисплеев в 80-е и 90-е годы), как на популярном терминале DEC VT100:


Терминал DEC VT100

Хотя технология улучшилась, но эта модель — терминал отправляет символы программе на компьютере, а он выдаёт текст для пользователя — осталась и сегодня как фундаментальная модель взаимодействия всех командных строк и консолей на всех платформах!


Архитектура терминала и командной строки

Модель по-своему элегантна. Одна из причин — в сохранении простоты и цельности каждого компонента: клавиатура выдаёт символы которые буферизуются как электрические сигналы. Устройство вывода просто выдаёт на дисплей (бумагу/экран) символы, полученные с компьютера.

На каждом этапе в системе передаётся только поток символов, так что это относительно простой процесс для внедрения различной инфраструктуры связи. Например, для добавления модемов, чтобы передавать потоки входных и выходных символов на большие расстояния по телефонным линиям.

Кодировка текста

Важно помнить, что терминалы и компьютеры обмениваются данными через потоки символов. При нажатии клавиши на клавиатуре терминала на подключенный компьютер отправляется значение, представляющее введённый символ. Нажмите клавишу ’A’ — и отправляется значение 65 (0x41). Нажмите ’Z’ — и отправляется 90 (0x5a).

7-битная кодировка ASCII

Список символов и их значений определён в стандарте American Standard Code for Information Interchange (ASCII), он же стандарт ISO/IEC 646 / ECMA-6 — «7-битный кодированный набор символов», который определяет:

  • 128 значений, представляющих печатные латинские символы A−Z (65-90), a−z (97−122), 0−9 (48−57)
  • Много общих знаков препинания
  • Несколько непечатаемых управляющих кодов (0−31 и 127):


Стандартные символы 7-битной ASCII

Когда 7 бит недостаточно: кодовые страницы

Однако 7 бит не обеспечивают достаточно места для кодирования многих диакритических знаков, знаков препинания и символов, используемых в других языках и регионах. Так что с добавлением дополнительного бита можно расширить таблицу символов ASCII дополнительными наборами «кодовых страниц» для символов 128−255 (и возможного переопределения нескольких непечатаемых символов ASCII).

Например, IBM ввела кодовую страницу 437 с несколькими графическими символами вроде ╫ (215) и ╣(185) и математическими, включая π (227) и ± (241), а также переопределила печатные символы для обычно непечатаемых символов 1−31:


Кодовая страница 437

Кодовая страница Latin-1 определяет множество символов, используемых языками на основе латиницы:


Кодовая страница Latin-1

Во многих окружениях командной строки и оболочках можно изменять текущую кодовую страницу, чтобы терминал отображал различные символы (в зависимости от доступных шрифтов), особенно для символов со значением 128−255. Но неправильно указанная кодовая страница приведёт к отображению кракозябр. И да, «кракозябры» — это настоящий термин! Кто бы мог подумать? ;)

Когда 8 бит недостаточно: Юникод

Кодовые страницы временно решили проблему, но у них много недостатков, например, они не позволяют отображать текст одновременно из нескольких кодовых страниц/языков. Таким образом, пришлось ввести новую кодировку, которая точно отображает каждый символ и алфавит для всех языков, известных человечеству, оставляя ещё много свободного места! Представляем Юникод.

Юникод — это международный стандарт (ISO/IEC 10646), который в данный момент определяет 137 439 символов из 146 современных и исторических письменностей, а также многие символы и глифы, в том числе многочисленные смайлики, которые широко используются практически в каждом приложении, платформе и устройстве. Юникод регулярно обновляется дополнительными системами письменности, новыми/исправленными смайликами, символами и т. д.

Юникод также определяет «непечатаемые» символы форматирования, которые позволяют, например, соединить символы и/или повлиять на предыдущие или последующие символы! Это особенно полезно в письменностях вроде арабской, где лигатура конкретного символа определяется окружающими. Эмодзи могут использовать соединительный символ нулевой ширины (zero width joiner), чтобы объединить несколько символов в один визуальный глиф. Например, эмодзи кота-ниндзя Microsoft формируются путём соединения кота с другими эмодзи:


Эмодзи кота-ниндзя Microsoft

Когда байтов слишком много: UTF-8!

Для уникального и систематического представления всех символов требуется большое пространство, до нескольких байт на каждый символ.

Поэтому для экономии было разработано несколько новых кодировок Юникода. Среди самых популярных — UTF-32 (4 байта на символ), UTF-16/UCS-2 (2 байта) и UTF-8 (1−4 байта на символ).

Во многом благодаря обратной совместимости с ASCII и экономии места UTF-8 стала самой популярной кодировкой Юникода в интернете. Она демонстрирует взрывной рост с 2008 года, когда обогнала по популярности ASCII и другие популярные кодировки:


Рост популярности кодировки UTF-8 (источник: Википедия)

Таким образом, поначалу терминалы поддерживали 7-битный, а затем 8-битный текст ANSI, но большинство современных терминалов поддерживают текст Unicode/UTF-8.

Итак, что такое командная строка и что такое оболочка?

«Командная строка» или CLI (интерфейс/интерпретатор командной строки) описывает самый фундаментальный механизм, через который человек управляет компьютером: CLI принимает введённый оператором ввод и выполняет требуемые команды.

Например, echo Hello отправляет текст «Hello» на устройство вывода (например, на экран). dir (Cmd) или ls (PowerShell/*NIX) перечисляет содержимое текущего каталога и т.д.

Раньше доступные команды были относительно простыми, но операторы требовали всё более изощрённых команд и возможности писать скрипты для автоматизации повторяющихся или сложных задач. Таким образом, процессоры командной строки стали сложнее и превратились в то, что теперь называют «оболочкой» командной строки (shell).

В Unix/Linux оригинальная оболочка Unix (sh) породила множество оболочек, включая Korn shell (ksh), C shell (csh) и Bourne Shell (sh). В свою очередь, на их основе создан Bourne Again Shell (bash) и т.д.

В мире Microsoft:

  • Оригинальный MS-DOS (command.com) был относительно простой оболочкой командной строки
  • «Командная строка» Windows NT (cmd.exe) разработана с учётом совместимым с устаревшими скриптами command.com, плюс добавлены несколько команд для новой, более мощной операционной системы
  • В 2006 году Microsoft выпустила Windows PowerShell
    • PowerShell — это современная объектная оболочка командной строки, которая позаимствовала функции других оболочек и включает в себя возможности .NET CLR и фреймворка .NET
    • С помощью PowerShell можно писать скрипты и автоматизировать практически все аспекты одного или нескольких компьютеров под Windows, сети, систем хранения данных, БД и т.д.
    • В 2017 году Microsoft открыла исходный код PowerShell, разрешив запуск на macOS, разных вариантах Linux и BSD
  • В 2016 году Microsoft представила подсистему Windows для Linux (WSL)
    • Позволяет запускать обычные немодифицированные двоичные файлы Linux непосредственно в Windows 10
    • Пользователи устанавливают один или несколько обычных дистрибутивов Linux из магазина Windows
    • Можно запустить один или несколько экземпляров дистрибутива параллельно с другими, а также параллельно с существующими приложениями и средствами Windows
    • WSL позволяет запускать бок о бок все инструменты Windows и инструменты командной строки Linux без использования ресурсоёмких виртуальных машин

Мы ещё вернёмся к оболочкам командной строки Windows, но пока запомним, что существуют разные оболочки, они принимают команды, введённые пользователем/оператором, и выполняют широкий спектр задач по мере необходимости.

Современная командная строка

Современные компьютеры значительно мощнее «тупых терминалов» прошлого и обычно работают под управлением десктопной ОС (например, Windows, Linux, macOS) с графическим пользовательским интерфейсом (GUI). Такое окружение GUI позволяет нескольким приложениям работать одновременно в отдельных окнах на экране и/или невидимо в фоновом режиме.


Cmd, PowerShell и Ubuntu Linux под WSL работают на независимых инстансах консоли

На смену громоздким, неповоротливым электромеханическим телетайпам пришли современные консольные/терминальные приложения, которые работают в окошке на экране компьютера, но по-прежнему выполняют такие же необходимые функции, как аппаратные терминалы из прошлого.

Аналогично и приложения командной строки, к которым подключены терминалы, работают как и раньше: получают входные символы, решают, что делать с этими символами, (необязательно) выполняют работу — и могут выдать текст для отображения пользователю. Только вместо связи по медленным каналам TTY терминальные приложения и приложения командной строки на одной машине общаются по очень скоростным каналам Pseudo Teletype (PTY) в памяти.


Современная командная строка

Современные терминалы в основном взаимодействуют с приложениями командной строки, запущенными локально. Но конечно, они также могут взаимодействовать с приложениями командной строки, запущенными на других машинах в той же сети или даже с удалёнными машинами на другой стороне света через интернет. Это «удалённое» взаимодействие с командной строкой — мощный инструмент, который популярен на каждой платформе, особенно на *NIX.

Эволюция командной строки

Скромное начало: MS-DOS

На заре компьютерной индустрии управление большинством компьютеров осуществлялось путём ввода команд в командной строке. За рыночную долю боролись компьютеры под Unix, CP/M, DR-DOS и других. В итоге система MS-DOS стала стандартом де-факто для IBM PC и всех совместимых компьютеров:


MS-DOS 6.0

Как и большинство основных операционных систем того времени, интерпретатор командной строки или «оболочка» в MS-DOS предоставляла простой, но относительно эффективный набор команд и синтаксис командных скриптов для написания batch-файлов (.bat).

Предприятия крупного и малого бизнеса очень быстро взяли на вооружение MS-DOS и в совокупности создали многие миллионы скриптов, некоторые из которых всё ещё используются сегодня! Batch-скрипты применяются для автоматизации настройки ПК, установки/изменения параметров безопасности, обновления программного обеспечения, сборки кода и т.д.

Вы редко или никогда не увидите реальную работу такого скрипта, потому что многие из них выполняются в фоновом режиме, например, при авторизации на компьютере. Но сотни миллиардов скриптов командной строки и команд выполняются каждый день только на Windows!

Командная строка представляет мощный инструмент в руках человека, который имеет терпение и упорство, чтобы научиться выжимать максимум из доступных команд и инструментов. Но большинству обычных пользователей сложно эффективно управлять компьютером из командной строки. Большинству не нравилось, что нужно изучать и запоминать много словно мистических аббревиатур, чтобы компьютер произвёл хоть какое-нибудь полезное действие.

Требуется более удобный и ориентированный на производительность пользовательский интерфейс.

Графический интерфейс идёт в мейнстрим

Добро пожаловать в графический интерфейс пользователя (GUI), изобретённый в Xerox Alto.

Вскоре после изобретения появилось много конкурирующих GUI на компьютерах Lisa и Macintosh от Apple, Commodore Amiga (Workbench), Atari ST (DRI GEM), Acorn Archimedes (Arthur/RISC OS), Sun Workstation, X11/X Windows и многих других, в том числе Microsoft Windows.

Windows 1.0 вышла в 1985 году и являлась по сути приложением MS-DOS, которое предоставляло простое окружение GUI с плиточным окном, позволяя пользователям запускать несколько приложений бок о бок:


Windows 1.01 на MS-DOS

Windows 2.x, 3.x, 95 и 98 работали на базе MS-DOS. Более поздние версии Windows начали заменять некоторые функции MS-DOS альтернативами Windows (например, операции с файловой системой), но все они полагались на фундамент MS-DOS.

Примечание: Windows ME (Millennium Edition) стала интересным гибридом. В ней наконец-то заменили поддержку MS-DOS и поддержку реального режима из предыдущих версий Windows несколькими новыми функциями (особенно технологии Gaming & Media). Некоторые функции позаимствованы из Windows 2000 (например, новый стек TCP/IP), но настроены для работы на домашних ПК, которым трудно запустить полноценную NT.

Но Microsoft понимала, что не может бесконечно растягивать архитектуру и возможности MS-DOS и Windows. Требовалась новая операционная система с прицелом на будущее.

Microsoft — лидер рынка Unix! Да, серьёзно!

Разрабатывая MS-DOS, Microsoft также занималась поставкой Xenix — фирменного порта Unix версии 7 — для различных процессорных и машинных архитектур, включая Z8000, 8086/80286 и 68000.

К 1984 году Xenix от Microsoft стал самым популярным вариантом Unix в мире!

Тем временем распад Bell Labs — родины Unix — привёл к появлению AT&T, которая начала продавать Unix System V производителям компьютеров и конечным пользователям.

Microsoft понимала, что отсутствие собственной ОС ставит под угрозу её способности для развития. Поэтому было принято решение отказаться от Xenix: в 1987 году Microsoft передала Xenix своему партнёру Santa Cruz Operation (SCO), с которым работала над несколькими проектами по портированию и улучшению Xenix на различных платформах.

Microsoft + IBM == OS/2… ненадолго

В 1985 году Microsoft начала работать с IBM над новой операционной системой OS/2. Она изначально планировалась как «более функциональная DOS» для некоторых современных 32-битных CPU и с учётом других технологий, которые быстро порождались в IBM и у других OEM.

Но история OS/2 оказалась слишком бурной. В 1990 году Microsoft и IBM прекратили сотрудничество. Это было обусловлено рядом факторов, в том числе значительными культурными различиями между разработчиками IBM и Microsoft, проблемами планирования, а также взрывным успехом и ростом внедрения Windows 3.1. IBM продолжала разработку и поддержку OS/2 до конца 2006 года.

К 1988 году Microsoft убедилась, что будущий успех требует более масштабного, смелого и амбициозного подхода. Такой подход потребует новой, современной операционной системы, которая будет поддерживать амбициозные цели компании.

Большая ставка Microsoft: Windows NT

В 1988 году Microsoft пригласила Дэйва Катлера, создателя популярной и уважаемой операционной системы VAX/VMS в компании DEC. Его задача — создать новую, современную, независимую от платформы операционную систему, которой Microsoft будет владеть, контролировать и на которой во многом построит своё будущее.

Этой новой операционной системой стала Windows NT: фундамент, на котором построены Windows 2000, Windows XP, Windows Vista, Windows 7, Windows 8 и Windows 10, а также во все версии Windows Server, Windows Phone 7+, Xbox и HoloLens!

Windows NT изначально спроектирована как кроссплатформенная система. Сначала она поддерживала Intel i860, затем MIPS R3000, Intel 80386+, DEC Alpha и PowerPC. С тех пор семейство ОС Windows NT портировали для поддержки процессорных архитектур IA64 Itanium, x64 и ARM/ARM64, среди прочих.

Windows NT предоставляет интерфейс командной строки через терминальное приложение Windows Console и командную строку Command Prompt (cmd.exe). Cmd разработан на максимальную совместимость с пакетными скриптами MS-DOS, чтобы помочь бизнесу перейти на новую платформу.

Мощь PowerShell

Cmd сохраняется в Windows по сей день (и, вероятно, сохранится в течение многих десятилетий). Поскольку его основная задача — обеспечить максимальную обратную совместимость, Cmd редко улучшается. Даже «исправление ошибок» зачастую затруднено, если эти «баги» существовали в MS-DOS или более ранних версиях Windows!

В начале 2000-х оболочка Cmd уже устарела: Microsoft и её клиенты срочно нуждались в более мощной и гибкой командной строке. Из этой потребности появился PowerShell (который возник из «Манифеста Монады» Джеффри Сновера).

PowerShell — это объектно-ориентированная оболочка, в отличие от оболочек на основе файлов/потоков, которые принято использовать в мире *NIX: вместо потоков текста PowerShell обрабатывает потоки объектов. Он предоставляет авторам скриптов возможность прямого доступа и манипуляций с объектами и их свойствами вместо написания множества скриптов для анализа и обработки текста (как sed/grep/awk/lex/др.).

Созданные на базе .NET Framework и среды Common Language Runtime (CLR), язык и синтаксис PowerShell разработаны для объединения богатства экосистемы .NET со многими распространёнными и полезными функциями из множества других языков сценариев оболочки с акцентом на то, чтобы скрипты обеспечивали максимальную консистентность и исключительную… ну… мощь. :)

Чтобы узнать больше о PowerShell, рекомендую прочитать книгу «PowerShell в действии» (Manning Press), написанную Брюсом Пайеттом — разработчиком синтаксиса и языка PowerShell. В частности, первые несколько глав содержат подробное обоснование структуры языка.

PowerShell был принят для использования многими технологиями на платформе Microsoft, включая Windows, Exchange Server, SQL Server, Azure и многими другими. Он предоставляет очень согласованные команды для администрирования и управления практически всеми аспектами Windows и/или среды.

PowerShell Core — это PowerShell с открытым исходным кодом, доступное для Windows и различных версий Linux, BSD и macOS.

POSIX для NT, Interix и служб UNIX

При проектировании NT компания команда Катлера специально разработала ядро NT и операционную систему для поддержки нескольких подсистем-интерфейсов между кодом пользовательского режима и основным ядром.

Когда в 1993 году вышла первая Windows NT версии 3.1, она поддерживала несколько подсистем: МЅ-DOS, Windows, OS/2 и POSIX v1.2. Эти подсистемы позволяли на одной машине и базовой ОС запускать приложения, нацеленные на несколько платформ операционной системы без виртуализации или эмуляции — это внушительная разработка даже по меркам сегодняшнего дня!

Оригинальная реализация POSIX в Windows NT была приемлемой, но для неё требовались значительных улучшения. Поэтому Microsoft приобрела Softway Systems и её POSIX-совместимую подсистему Interix для NT. Изначально Interix поставлялась как отдельное дополнение, а затем её объединили с несколькими полезными утилитами и инструментами и выпустили в виде Services For Unix (SFU) в Windows Server 2003 R2 и Windows Vista. Однако поддержку SFU пришлось прекратить после Windows 8, в основном, из-за недостаточной популярности.

А потом произошла забавная вещь…

Windows 10 — новая эра для командной строки Windows!

В начале разработки Windows 10 компания открыла страницу UserVoice с вопросом, какие функции люди хотят реализовать в различных областях ОС. Сообщество разработчиков особенно громко требовало от Microsoft две вещи:

  1. Внести значительные улучшения в консоль Windows
  2. Предоставить пользователям возможность запускать средства Linux в Windows

На основе этих отзывов Microsoft сформировала две новые группы:

  1. Группа разработки Windows Console и командной строки, которой поручили провести капитальный ремонт инфраструктуры Windows Console и командной строки
  2. Группа разработки Windows Subsystem for Linux (WSL)

Остальное, как говорится, история!

Подсистема Windows для Linux (WSL)

Основанные на GNU/Linux «дистрибутивы» (сочетания ядра Linux и коллекций инструментов пользовательского режима) становятся всё популярнее, особенно на серверах и в облаке. Хотя в Windows имелась POSIX-совместимая среда выполнения, но SFU не мог запускать многие инструменты и двоичные файлы Linux из-за дополнительных системных вызовов и различий в поведении по сравнению с традиционной Unix/POSIX.

После анализа обратной связи от разработчиков и технически подкованных пользователей Windows, а также в связи с растущим спросом внутри самой Microsoft, компания изучила несколько вариантов, и в конечном итоге решила позволить на Windows запуск оригинальных немодифицированных бинарных файлов Linux!

В середине 2014 года Microsoft сформировала группу разработки того, что станет подсистемой Windows для Linux (WSL). WSL впервые анонсировали в сборке Build 2016, а вскоре предварительная версия вышла на канале Windows 10 Insider.

С тех пор WSL обновляется в большинстве инсайдерских сборок и в каждом крупном выпуске ОС с момента Anniversary Update осенью 2016 года. В каждой новой версии увеличивается функциональность, совместимость и стабильность WSL: в первой версии это был интересный эксперимент, который мог запускать лишь несколько распространённых программ Linux. При активной помощи сообщества (всем спасибо!) разработчики быстро дорабатывали WSL, так что вскоре она получила много новых возможностей и научилась запускать всё более сложные бинарники Linux.

Сегодня (середина 2018 года) WSL запускает большинство двоичных файлов Linux, программы, компиляторы, компоновщики, отладчикии т.д. Многие разработчики, IT-специалисты, инженеры DevOps и многие другие, кому необходимо запускать или создавать инструменты, приложения, службы Linux и т. д., получили резкое повышение производительности и возможность запускать свои любимые инструменты Linux вместе с любимыми инструментами для Windows на одном компьютере, без загрузки двух операционных систем.

Команда WSL продолжает улучшать WSL в части выполнения задач Linux, повышения производительности и интеграции с Windows.

Перезагрузка и капитальный ремонт Windows Console

В конце 2014 года проект по созданию подсистемы Windows для Linux (WSL) шёл полным ходом, и на фоне взрыва оживлённого интереса пользователей к командной строке стало очевидно, что консоль Windows явно нуждается в некотором апгрейде.

В частности, консоли не хватало многих функций, привычных для современных *NIX-совместимых систем, таких как возможность парсинга и вывода последовательностей ANSI/VT, широко используемых в мире *NIX для вывода насыщенного и подсвеченного текста и текстовых UI.

В чём тогда смысл разработки WSL, если пользователь не сможет корректно использовать инструменты Linux?

Ниже пример того, что отображает консоль Windows 7 и Windows 10: обратите внимание, что Windows 7 (слева) не в состоянии правильно отобразить VT, сгенерированный линуксовыми программами tmux, htop, Midnight Commander и cowsay, но они корректно выглядят в Windows 10 (справа):


Сравнение консоли Windows 7 и Windows 10

Так, в 2014 году была сформирована небольшая «группа Windows Console». На неё возложили задачу распутать, понять и улучшить кодовую базу Windows Console… которой к этому времени было около 28 лет — больше, чем программистам, которые работают над этим проектом.

Как подтвердит любой разработчик, которому когда-либо приходилось брать старый, грязный, плохо поддерживаемый код, улучшение такого кода представляет собой сложную задачу. Ещё сложнее не нарушить существующее поведение. Для обновления самой часто запускаемой программы в Windows, не нарушив работу миллионов клиентских скриптов, инструментов, скриптов авторизации, систем сборки, производственных систем, систем анализа и прочих, требуется немало «внимания и терпения». ;)

Для разработчиков проблема усугубилась, когда они поняли всю строгость требований к консоли со стороны клиентов. Например, если производительность консоли изменялась на 1−2% от сборки к сборке, то срабатывали сигналы тревоги в группе Windows Build, что приводило… гм… к «быстрой и прямой обратной связи», то есть требованию немедленного исправления.

Итак, когда мы будем обсуждать улучшения консоли и новые функции, помните, что есть несколько незыблемых принципов, которым должно соответствовать каждое изменение, в том числе:

  1. НЕ допускать новых уязвимостей
  2. НЕ ломать инструменты, скрипты, команды и т. д. у существующих клиентов (внутренних или внешних)
  3. НЕ снижать производительность и не увеличивать потребление памяти/IO (без чётких и хорошо доведённых причин)

За последние три года команда Windows Console провела следующую работу:

  • Капитальный ремонт внутренних компонентов
    • Значительное упрощение и уменьшение кодовой базы
    • Замена нескольких внутренних коллекций, списков, стеков и т.д. контейнерами STL
    • Разбиение на модули и изоляция логических и функциональных единиц кода, что позволяет улучшать функции (а иногда и заменять их), не «ломая мир»
  • Объединение нескольких ранее отдельных и несовместимых консольных движков в один
  • МНОЖЕСТВО улучшений безопасности и надёжности
  • Возможность парсинга и вывода последовательностей ANSI/VT, что позволяет консоли точно отображать насыщенный текстовый вывод из *NIX и других современных инструментов командной строки и приложений
  • Поддержка 24-битного цвета вместо прежних 16 цветов!
  • Улучшенная безбарьерность: Narrator и другие приложения безбарьерной среды работают в окне консоли
  • Добавлена/улучшена поддержка мыши и сенсорного ввода

И работа продолжается! В настоящее время мы завершаем реализацию нескольких захватывающих новых функций.

К чему был этот урок истории?

Я надеюсь, вы поняли, что командная строка остаётся ключевым компонентом стратегии, платформы и экосистемы Microsoft.

Хотя для конечных пользователей Microsoft продвигала графический интерфейс, сама компания и её технические клиенты/пользователи/партнёры в значительной степени полагались на командную строку для выполнения множества технических задач.

На самом деле Microsoft буквально не смогла бы создать ни Windows, ни любой другой из своих программных продуктов без быстрой, эффективной, стабильной и безопасной консоли!

На протяжении эпох MS-DOS, Unix, OS/2 и Windows командная строка оставалась, пожалуй, самым важным инструментом в наборе инструментов каждого технического пользователя. Даже многие пользователи, которые никогда не вводили команды в окно, в реальности используют консоль каждый день! Даже сборка кода в Visual Studio (VS) происходит в скрытом окне консоли. При использовании Exchange Server или средств администрирования SQL Server многие из этих команд выполняются с помощью PowerShell в скрытой консоли.

Механика Windows Console

Во время начала разработки Windows NT в 1989 году не было ни графического интерфейса, ни рабочего стола. Была только полноэкранная командная строка, которая визуально напоминала MS-DOS. Когда появилась реализация графического интерфейса Windows, потребовалось создать приложение консоли для GUI — и таким образом родилась Windows Console! Это одно из первых приложений Windows NT с графическим интерфейсом и, безусловно, одно из старейших приложений Windows, которое по-прежнему используется повсеместно!

Кодовой базе консоли Windows в настоящее время (июль 2018 года) почти 30 лет… по сути, больше, чем разработчикам, которые сейчас над ней работают!

Что делает консоль?

Как мы узнали ранее, у терминала относительно простой алгоритм работы:

  • Обработать пользовательский ввод
    • Принять входной сигнал от приборов, включая клавиатуру, мышь, тачскрин и др.
    • Перевести ввод в соответствующие символы и/или последовательности ANSI/VT
    • Отправить символы в подключенное приложение/инструмент/оболочку
  • Обработать вывод приложения:
    • Принять вывод текста из покдлюченного приложения/инструмента командной строки
    • Обновлять экран по мере необходимости, основываясь на полученных данных от приложения (например, полученный текст, перемещения курсора, изменение цвета текста и т.д.)
  • Обработать системные взаимодействия:
    • Запуск по запросу
    • Управление ресурсами
    • Изменение размера/развернуть окно/свернуть окно и т.д.
    • Завершение по запросу или после закрытия канала связи

Но консоль Windows работает немного иначе:

Механика Windows Console

Консоль Windows — обычный исполняемый файл Win32. Изначально он написан на C, но большая часть кода сейчас переносится на C++ по мере того, как разработчики модернизируют и разбивают на модули кодовую базу.

Если вам интересны такие вещи: многие спрашивали, Windows написана на C или C++. Ответ такой: несмотря на объектно-ориентированный дизайн NT, как и большинство ОС, Windows почти полностью написана на C! Почему? Потому что C++ увеличивает потребление памяти и привносит накладные расходы на выполнение кода. Даже сегодня скрытые затраты на выполнение кода C++ могут удивить, но ещё в 1990-х, когда память стоила около $60/МБ (да… $60 за МЕГАБАЙТ!), скрытые затраты на vtables и прочее были значительными. Кроме того, затраты на косвенное обращение к виртуальным методам и разыменование объектов в то время могли привести к очень значительным потерям производительности и масштабированию кода C++. В наше время нужно соблюдать осторожность, но издержки производительности C++ на современных компьютерах вызывают намного меньше беспокойства. Часто это приемлемый компромисс, учитывая безопасность, читабельность и лучшую сопровождаемость кода… именно поэтому мы постепенно переписываем код консоли на современном C++!

Так что внутри консоли Windows?

До Windows 7 инстансы консоли Windows размещались в критически важной подсистеме Client Server Runtime Subsystem (CSRSS)! Но в Windows 7 из соображений безопасности и надёжности консоль переместили из CSRSS в следующие бинарники:

  • conhost.exe — пользовательский режим консоли Windows UX и механика командной строки
  • condrv.sys — драйвер ядра Windows, обеспечивающий коммуникации между conhost и одной или несколькими оболочками командной строки/инструментами/приложениями

Высокоуровневая схема текущей внутренней архитектуры консоли выглядит следующим образом:

Ядро консоли состоит из следующих компонентов (снизу вверх):

  • ConDrv.sys — драйвер режима ядра
    • Обеспечивает высокопроизводительный канал связи между консолью и любыми подключенными приложениями командной строки
    • Переносит туда и обратно сообщения IO Control (IOCTL) между приложениями командной строки и консолью, к которой они «прикреплены»
    • Консольные сообщения IOCTL содержат:
      • Данные, представляющие запросы на выполнение вызовов API для экземпляра консоли
      • Текст, отправляемый из консоли в приложение командной строки
  • ConHost.exe — приложение Win32 GUI:
    • ConHost Core — внутренности и механика
      • Сервер API: преобразует сообщения IOCTL, полученные из приложений командной строки, в вызовы API и отправляет текстовые записи из консоли в приложение командной строки
      • API: реализует консольный API Win32 и логику для всех операций, которые консоль может попросить выполнить
      • Буфер ввода: хранит записи событий клавиатуры и мыши, генерируемые пользовательским вводом
      • VT Parser: если включен, анализирует последовательности VT, извлекает их из текста и генерирует эквивалентные вызовы API
      • Буфер вывода: хранит текст, отображаемый на дисплее консоли. По сути, это 2D-массив структур CHAR_INFO, которые содержат символьные данные и атрибуты каждой ячейки (подробнее о буфере ниже)
      • Другое: в схему не включены инфраструктура сохранения/извлечения значений из реестра и/или файлов ярлыков и т.д.
    • Console UX App Services — слой UX и UI
      • Управляет макетом, размером, положением и прочими характеристиками окна консоли на экране
      • Отображает и обрабатывает параметры UI и т.д.
      • Прокачивает очередь сообщений Windows, обрабатывает их и преобразует введённые пользователем данные в записи событий клавиш и мыши, сохраняя их во входном буфере

Windows Console API

Как видно из схемы архитектуры, в отличие от терминалов NIX, консоль отправляет/получает вызовы API и/или данные в виде сообщений IO Control (IOCTL), а не текста! Даже встроенные в текст последовательности ANSI/VT из приложений командной строки (в основном Linux), извлекаются, анализируются и преобразуются в вызовы API!

Это различие раскрывает ключевое фундаментальное философское различие между *NIX и Windows: в *NIX «всё является файлом», а в Windows «всё является объектом»!

У обоих подходов есть преимущества и недостатки, которые мы перечислим, но не будем подробно обсуждать. Просто помните, что это ключевое различие в философии объясняет многие фундаментальные различия Windows и *NIX!

В *NIX всё является файлом

Когда Unix впервые появился в конце 1960-х и начале 1970-х годов, одним из основных принципов стало то, что (где это возможно) всё следует абстрагировать как файловый поток. Одна из ключевых целей заключалась в упрощении кода для доступа к устройствам и периферии: если все устройства представляются в ОС как файлы, то коду легче получить к ним доступ.

Эта философия работает на самом глубоком уровне: можно даже перемещаться и опрашивать большую часть конфигурации ОС и компьютера под *NIX, перемещаясь по псевдо/виртуальным файловым системам, которые показывают то, что кажется «файлами» и папками, но на самом деле представляет собой конфигурацию машины и оборудование.

Например, в Linux можно исследовать свойства процессоров, изучая содержимое псевдофайла /proc/cpuinfo:

Но простота и согласованность этой модели могут дорого стоить: извлечение/анализ конкретной информации в псевдофайлах часто требует специальных инструментов, таких как sed, awk, perl, python и т.д. Эти инструменты используются для написания команд и скриптов парсинга текстового содержимого, поиска определённых шаблонов, полей и значений. Некоторые из скриптов могут быть довольно сложными, часто трудными в обслуживании и хрупкими — если структура, шаблон и/или формат текста изменятся, многие скрипты, вероятно, потребуется обновить.

В Windows всё является объектом

Когда проектировалась Windows NT, «объекты» рассматривались как будущее в разработке программного обеспечения: «объектно-ориентированные» языки программирования появлялись быстрее, чем тараканы: Simula и Smalltalk уже зарекомендовали себя, а C++ набирал популярность. За ними последовали другие объектно-ориентированные языки, в том числе Python, Eiffel, Objective-C, ObjectPascal/Delphi, Java, C# и многие другие.

Результат предсказуем. Созданная в те пьянящие, объектно-ориентированные дни (около 1989 года) Windows NT разработана с философией, что «всё является объектом». На самом деле одной из самых важных частей ядра NT является Менеджер объектов!

Windows NT предоставляет богатый набор Win32 API для получения и/или управления объектами ОС. Разработчики используют Win32 API для сбора и представления информации, похожей на данные из псевдофайлов и инструментов *NIX, только через объекты и структуры. А поскольку парсеры, компиляторы и анализаторы понимают структуру объектов, то многие ошибки кодирования часто проявляются на ранней стадии, что помогает проверить синтаксическую и логическую правильность намерений программиста. Со временем это может привести к уменьшению сбоев, волатильности и лучшему порядку.

Итак, возвращаясь к основной дискуссии о консоли Windows: команда NT решила построить «консоль», отличную от традиционного терминала *NIX в нескольких ключевых областях:

  • Console API: вместо того, чтобы полагаться на способность программистов генерировать корректные ANSI/VT-последовательности, которые трудно проверить, консоль Windows управляется через богатые консольные API
  • Общие службы: чтобы избежать дублирования служб во всех оболочках командной строки (например, журнал команд, псевдонимы команд), консоль сама предоставляет некоторые из них через Console API

Проблемы с консолью Windows

Хотя консольные API стали очень популярны в инструментах и сервисах командной строки, но ориентированная на API модель имеет определённые недостатки, перечисленные ниже.

Только для Windows

Многие средства командной строки и приложения широко используют Console API.

В чём проблема? Они работают только под Windows.

Таким образом, в сочетании с другими различиями (например, в жизненном цикле и т.д.), приложения командной строки Windows не всегда легко переносятся под *NIX и наоборот.

Из-за этого в экосистеме Windows распространены свои собственные, часто похожие, но обычно отличающиеся средства командной строки и приложения. Это означает, что при использовании Windows пользователям приходится изучать один набор приложений и инструментов командной строки, оболочек, языков сценариев и т.д., а при использовании *NIX — другой набор.

У этой проблемы нет простого решения: консоль Windows и командную строку нельзя просто выбросить и заменить на bash и iTerm2 — существуют сотни миллионов приложений и сценариев, которые зависят от консоли Windows и оболочек Cmd/PowerShell.

Сторонние инструменты, такие как Cygwin, отлично переносят многие основные инструменты GNU и библиотеки совместимости в Windows, но не могут запускать непортированные, неизменённые бинарники Linux. Это очень важно, так как многие пакеты и модули Ruby, Python, Node зависят от бинарных файлов Linux и/или зависят от поведения *NIX.

Эти причины привели к тому, что Microsoft расширила совместимость с Windows, разрешив запуск аутентичных двоичных файлов и средств Linux в подсистеме Windows для Linux (WSL). С помощью WSL пользователи теперь могут загружать и устанавливать один или несколько дистрибутивов Linux бок о бок на одной машине, а также использовать apt/zypper/npm/gem/др. для установки и запуска подавляющего большинства инструментов командной строки Linux вместе с их любимыми приложениями и инструментами Windows.

Тем не менее, у нативной консоли остаётся функциональность, которая отсутствует в сторонних терминалах: в частности, Windows Console предоставляет сервисы command-history и command-alias, чтобы каждой оболочке (в частности) не пришлось повторно реализовать одинаковую функциональность.

Сложности с удалённой работой

Как говорилось в начале статьи, терминалы изначально были отделены от компьютера, к которому подключены. Сегодня эта конструкция сохраняется: большинство современных терминалов и оболочек/приложений/проч. командной строки изолированы в рамках отдельных процессов и/или машин.

На *NIX-платформах парадигма изолированности терминалов и приложений командной строки с простым обменом символами привела к тому, что там легко получить доступ и работать с удалённого компьютера/устройства. Если терминал и приложение командной строки обмениваются потоками символов по какой-то упорядоченной инфруструктуре (TTY, PTY и т.д.), то очень легко работать удалённо.

Но в Windows многие приложения командной строки зависят от вызова API консоли и предполагают выполнение на той же машине, что и сама консоль. Это затрудняет удалённое управление. Как приложению командной строки удалённо обратиться к API на консоли локального компьютера? Хуже того, как удалённое приложение обратится к Console API, если доступ к нему осуществляется через терминал на Mac или Linux?!

Извините, что дразню вас, но более подробно мы вернёмся к этой теме в следующей статье.

Запуск консоли… или нет!

Когда пользователь *NIX хочет запустить инструмент командной строки, то сначала запускает терминал. Тот затем запускает оболочку по умолчанию или может быть настроен для запуска определённого приложения/инструмента. Терминал и приложение командной строки взаимодействуют потоками символов через Pseudo TTY (PTY).

Однако в Windows всё работает иначе: пользователи Windows никогда не запускают консоль (conhost.exe) — они сразу запускают оболочки командной строки и приложения, например, Cmd.exe, PowerShell.exe, wsl.exe и прочее. Windows подключает запущенное приложение к текущей консоли (если оно запущено из командной строки) или к вновь созданному экземпляру консоли.

#SAYWHATNOW?

Да, в Windows пользователи запускают приложение командной строки, а не саму консоль.

Если пользователь запускает приложение командной строки из существующей оболочки командной строки, то Windows обычно присоединяет вновь запущенный .exe к текущей консоли. В противном случае Windows запустит новый экземпляр консоли, к которому будет присоединено только что запущенное приложение.

Немного занудства: многие говорят, что «приложения командной строки запускаются в консоли». Это не так и приводит к большой путанице относительно того, как в реальности работает консоль и приложения командной строки! Приложения командной строки и их консоли запускаются в независимых процессах Win32. Помогите исправить это заблуждение. Всегда говорите, что «средства командной строки/приложения выполняются с подключением к консоли». Спасибо!

Звучит неплохо, правда? На самом деле… нет. Есть некоторые проблемы:

  1. Консоль и приложение командной строки взаимодействуют сообщениями IOCTL через драйвер, а не через текстовые потоки
  2. Windows указывает, что ConHost.exe — это консольное приложение, подключенное к приложениям командной строки
  3. Windows создаёт «каналы» (pipes), по которым взаимодействуют консоль и приложение командной строки

Это существенные ограничения. Что если вы хотите создать альтернативное консольное приложение для Windows? Как отправить события с клавиатуры/мыши и прочие действия пользователя в приложение командной строки, если нельзя получить доступ к каналам, соединяющим консоль с этим приложением?

Увы, ситуация тут не очень хорошая. Есть отличные сторонние консоли и серверные приложения для Windows (например, ConEmu/Cmder, Console2/ConsoleZ, Hyper, Visual Studio Code, OpenSSH и т. д.), но им приходится прибегать к изощрённым трюкам, чтобы работать как обычная консоль!

Например, сторонним консолям приходится запускать приложение командной строки вне экрана, скажем, с координатами (-32000, -32000). Затем отправлять нажатия клавиш на внеэкранную консоль, скрапить с экрана текстовое содержимое внеэкранной консоли — и повторно выводить его в собственном пользовательском интерфейсе!

Какое-то безумие, верно?! Тот факт, что эти приложения вообще работают — лишь доказательство изобретательности и целеустремленности их создателей.

Очевидно, что мы стремимся исправить эту ситуацию. Об этом тоже расскажем в следующих статьях.

Windows Console и VT

Как описано выше, консоль Windows предоставляет богатый API. С помощью Console API приложения и инструменты командной строки пишут текст, изменяют его цвет, перемещают курсор и т.д. И благодаря этим API не нужно было поддерживать последовательности ANSI/VT, которые обеспечивают похожую функциональность на других платформах.

Фактически, до Windows 10 в консоли Windows была реализована только минимальная поддержка последовательностей ANSI/VT:

Всё изменилось в 2014 году, когда Microsoft сформировала новую группу разработки Windows Console. Одним из её главных приоритетов стало реализовать всестороннюю поддержку последовательностей ANSI/VT для визуализации выходных данных приложений *NIX, работающих в подсистеме Windows для Linux (WSL) и на удалённых машинах *NIX.

Группа быстро внедрила в консоль Windows 10 всестороннюю поддержку последовательностей ANSI/VT, что позволило пользователям использовать и наслаждаться огромным набором инструментов и приложений командной строки Windows и Linux.

Команда продолжает улучшать поддержку VT с каждым выпуском ОС и будет благодарна за любые проблемы, которые вы упомянете в нашем трекере на GitHub. ;)

Обработка Юникода

К сожалению, консоль Windows и её API появились до изобретения Юникода!

Консоль Windows хранит текст (который впоследствии выводится на экран) как символы кодировки UCS-2 с двумя байтами на символ. Эта кодировка поддерживает кодирование первых 65536 позиций символов, что известно как плоскость 0 или основная многоязычная плоскость (Basic Multilingual Plane, BMP).

Приложения командной строки выводят текст в консоли с помощью Console API. Обрабатывающие текст интерфейсы, бывают двух видов: функции с суффиксом А обрабатывают однобайтовые/символьные строки, функции с суффиксом W обрабатывают двухбайтовые (wchar)/символьные строки.

Например, функция WriteConsoleOutputCharacter компилируется в WriteConsoleOutputCharacterA() для проектов ASCII или в WriteConsoleOutputCharacterW() для проектов на Юникоде. Код может напрямую вызвать функцию с суффиксом ...A или ...W, если необходима обработка конкретного типа.

Примечание: каждый W API поддерживает UCS-2, потому что это всё, что существовало в момент разделения на A/W, и мы думали, что так будет хорошо. Но многие W API уже обновились для поддержки ещё и UTF-16 на том же канале.

Не все W API понимают UTF-16, но все они знают хотя бы UCS-2.

Кроме того, консоль не поддерживает некоторые новые функции Юникода, включая соединительные символы нулевой ширины (zero width joiner), которые используются для объединения отдельных символов в арабских и индийских письменностях, а также для объединения символов эмодзи в один визуальный глиф.

Как же ввести эмодзи кота-ниндзя или сложные многобайтовые китайские/арабские символы в консоль? К сожалению, никак!

Мало того что консольный API не поддерживает символы Юникод больше двух байт на глиф (эмодзи NinjaCat требует 8 байт!), но внутренний буфер UCS-2 консоли тоже не может хранить дополнительные байты данных. Что ещё хуже, текущий GDI-рендерер консоли не сможет отрисовать глиф, даже если тот поместится в буфер!

Эх… Таковы радости legacy-кода.

Здесь опять я намерен прервать рассказ — вернёмся к этой теме в следующей статье. Оставайтесь с нами!

Итак, на чём мы остановились?

Дорогой читатель, если вы прочитали всё вышенаписанное, спасибо вам, и примите поздравления — теперь вы знаете больше о консоли Windows, чем большинство ваших друзей, и, вероятно, даже больше, чем вы сами хотели узнать! Какая удача!

Мы многое рассмотрели в этой статье:

  • Основные строительные блоки консоли Windows:
    • Condrv.sys — коммуникационный драйвер
    • ConHost.ехе — UX консоли и механика:
      • Сервер API — сериализует вызовы API и текстовые данные с помощью сообщений IOCTL, отправляемых в/из драйвера
      • API — функциональность консоли
      • Буферы — буфер ввода, хранящий пользовательский ввод, и буфер вывода, хранящий выходной/отображаемый текст
      • Парсер VT — преобразует последовательности ANSI/VT из текстового потока в вызовы API
      • UX консоли — состояние UI консоли, настройки, функции
      • Другое — технические данные, безопасность и проч.
  • Что делает консоль
    • Отправляет пользовательский ввод в подключенное приложение командной строки
    • Получает и отображает выходные данные из подключенного приложения командной строки
  • Чем консоль отличается от терминалов *NIX
    • NIX: «Всё представляет собой файл/текстовый поток»
    • Windows: «Все представляет собой объект, доступный через API»
  • Проблемы консоли
    • Консольные приложения и приложения командной строки взаимодействуют через запросы вызовов API и текст, сериализованный в Сообщения IOCTL
    • Консольный API могут вызвать только приложения командной строки Windows
      • Сложнее портировать приложения на/из Windows
    • Приложения взаимодействуют с консолью через Windows API
      • Затрудняет удалённое взаимодействие с приложениями и средствами командной строки Windows
    • Зависимость от IOCTL нарушает схему «обмен символами» терминала
      • Затрудняет эксплуатацию инструментов командной строки удалённого с не-Windows машин
    • Запуск приложений командной строки Windows является «необычным»
      • К приложениям командной строки можно присоединить только ConHost.exe
      • Сторонние терминалы вынуждены создавать внеэкранную консоль, отправлять туда символы и скрапить экран
    • Windows исторически не понимает последовательности ANSI/VT
      • В основном исправлено в Windows 10
    • У консоли ограниченная поддержка Юникода и в настоящее время проблемы с хранением и рендерингом UTF-8 и глифов, которые нуждаются в соединительных символах нулевой ширины

В следующих нескольких статьях этой серии мы более подробно разберём консоль и обсудим решение этих проблем… и не только!

Как всегда, следите за обновлениями.

Командная строка in Windows 10
Тип Commandлиния переводчик

Когда вы входите в систему UNIX, ваш главный интерфейс к системе называется UNIX SHELL. Это программа, которая отображает подсказку со знаком доллара ($). Это приглашение означает, что оболочка готова принять введенные вами команды. В системе UNIX можно использовать более одной разновидности оболочки.

На каком языке используется командная строка Windows?

Кстати, термин «Командная строка» относится к фактическому фрагменту текста, который означает, где вы должны ввести следующую команду в CLI. (например: C:> или # и т. д.). Windows использует пакетную обработку. Самый популярный язык в Linux — bash, но есть альтернативы.

Командная строка Windows — это оболочка?

Что такое командная строка Windows? Командная строка Windows (также известная как командная строка, cmd.exe или просто cmd) — это командная оболочка, основанная на операционной системе MS-DOS 1980-х годов, которая позволяет пользователю напрямую взаимодействовать с операционной системой.

Как вы запускаете команды Unix в командной строке Windows?

Запускать команды UNIX / LINUX в ​​Windows

  1. Перейдите по ссылке и загрузите файл установки Cygwin .exe — нажмите здесь. …
  2. После загрузки файла setup.exe дважды щелкните файл .exe, чтобы начать процесс установки.
  3. Нажмите кнопку «Далее», чтобы продолжить установку.
  4. Оставьте вариант по умолчанию, выбранный как «Установить из Интернета», и нажмите «Далее».

18 колода 2014 г.

Что такое полная форма CMD?

Председатель и управляющий директор (CMD) является главным исполнительным директором Корпорации и подотчетен Совету директоров.

CMD EXE — это вирус?

Cmd.exe — это вирус? Нет это не так. Настоящий файл cmd.exe — это безопасный системный процесс Microsoft Windows, который называется «Командный процессор Windows». Однако авторы вредоносных программ, таких как вирусы, черви и трояны, намеренно присваивают своим процессам одно и то же имя файла, чтобы избежать обнаружения.

На чем написано CMD?

Смешивание — не редкость. Но CMD по-прежнему в основном C, а не C ++. Его команды и функции поддержки реализованы как функции C, такие как eExit, eChdir, ParseStatement, SearchForExecutable и ExecPgm. Они не перенесли весь этот старый код C в дизайн ООП.

Как мне написать в CMD?

Использование скрипта CMD для открытия блокнота

  1. Введите CMD в меню «Пуск» Windows и нажмите Enter, чтобы открыть CMD.exe.
  2. Измените каталог с папки с текущим именем пользователя на базовый каталог, набрав «cd» и нажав Enter. …
  3. Введите следующую строку и нажмите Enter: запустите notepad.exe «c: windowssystem32».

CMD реально?

Врожденная мышечная дистрофия (ВМД)

Стоит ли изучать cmd или PowerShell?

Powershell может делать все, что умеет командная строка. Вы даже можете запускать старые инструменты командной строки из Powershell. (Использование Windows PowerShell для запуска старых инструментов командной строки). Я считаю, что вам следует сосредоточиться на изучении Powershell и изучать только те инструменты командной строки, для которых у Powershell нет командлетов.

CMD — это терминал?

Итак, cmd.exe не является эмулятором терминала, потому что это приложение Windows, работающее на машине Windows. … Cmd.exe — это консольная программа, а их очень много. Например, telnet и python — это консольные программы. Это означает, что у них есть окно консоли, это монохромный прямоугольник, который вы видите.

Что лучше cmd или PowerShell?

PowerShell сложнее традиционной командной строки, но при этом намного мощнее. Командная строка значительно уступает оболочкам, доступным для Linux и других Unix-подобных систем, но PowerShell уступает ей.

Можете ли вы запустить Unix в Windows?

Cygwin — самый популярный (и бесплатный) эмулятор Linux / UNIX для запуска из Windows. Я бы порекомендовал немного более продвинутое подмножество Cygwin / X, поскольку мы планируем открывать всплывающие окна с удаленных серверов на нашем компьютере с Windows. Загрузите установщик Cygwin, setup.exe.

Можем ли мы запускать команды Linux в Windows?

Подсистема Windows для Linux (WSL) позволяет запускать Linux внутри Windows. … Вам просто нужно скачать и установить его, как любое другое приложение для Windows. После установки вы можете запускать все нужные команды Linux.

Как использовать Linux в Windows?

Виртуальные машины позволяют запускать любую операционную систему в окне на рабочем столе. Вы можете установить бесплатный VirtualBox или VMware Player, скачать файл ISO для дистрибутива Linux, такого как Ubuntu, и установить этот дистрибутив Linux внутри виртуальной машины, как если бы вы устанавливали его на стандартном компьютере.

A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and providing information to them as to what actions they are to perform. In some cases the invocation is conditional based on conditions established by the user or previous executables. Such access was first provided by computer terminals starting in the mid-1960s. This provided an interactive environment not available with punched cards or other input methods.

Today, many users rely upon graphical user interfaces and menu-driven interactions. However, some programming and maintenance tasks may not have a graphical user interface and use a command line.

Alternatives to the command-line interface include text-based user interface menus (for example, IBM AIX SMIT), keyboard shortcuts, and various desktop metaphors centered on the pointer (usually controlled with a mouse). Examples of this include the Microsoft Windows, DOS Shell, and Mouse Systems PowerPanel. Command-line interfaces are often implemented in terminal devices that are also capable of screen-oriented text-based user interfaces that use cursor addressing to place symbols on a display screen.

Programs with command-line interfaces are generally easier to automate via scripting.

Many software systems implement command-line interfaces for control and operation. This includes programming environments and utility programs.

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 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. 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’ can be any program that constitutes the user-interface, including fully graphically oriented ones. For example, the default Windows GUI is a shell program named EXPLORER.EXE, as defined in the SHELL=EXPLORER.EXE line in the WIN.INI configuration file. These programs are shells, but not CLIs.

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.[1] In 1964, MIT Computation Center staff member Louis Pouzin developed the RUNCOM tool for executing command scripts while allowing argument substitution.[2] 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.[3] Pouzin returned to his native France in 1965, and the first Multics shell was developed by Glenda Schroeder.[2]

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.[4][5] 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).[5]

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. 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. 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, 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. 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 interface[6][7] is:

Prompt command param1 param2 param3 … paramN
  • Prompt — generated by the program to provide context for the user.
  • Command — provided by the user. Commands are usually one of three classes:
    1. Internal commands are recognized and processed by the command line interpreter.
    2. Included commands run separate executables.
    3. External commands run executable files that may be included by other parties.
  • param1 …paramN — parameters provided by the user. The format and meaning of the parameters depends upon the command. In the case of Included or 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, 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 toFiles
  • doSomething how sourceFile destinationFile
  • doSomething how < inputFile > outputFile
  • doSomething 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.

CLI and resource protection[edit]

One can modify the set of available commands by modifying which paths appear in the PATH environment variable. Under Unix, 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. OS2MDOSE.EXE instead of OS2E.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 Windows CMD.EXE does this. 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]

Prompt of a BBC Micro after switch-on or hard reset

«Command prompt» redirects here. For the Windows component named Command Prompt, see cmd.exe.

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 $, %, #,[8][9] :, > or -[10] 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),[11] 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».[12] 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]

An MS-DOS command line, illustrating parsing into command and arguments

A command-line argument or parameter is an item of information provided to a program when it is started. 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:

«file.s» is a command-line argument which tells the program rm to remove the file «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. 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[10] 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», 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 beginning 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.
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 =; thus Prog -fFilename, Prog -f Filename, Prog -f:Filename, Prog -f=Filename.
  • Some programs allow single-character options to be combined;[10] others do not. The switch -fA may mean the same as -f -A,[10] 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.[13] 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.[10] Also, the current setting is reflected also in the built-in help screens.[10] 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.[14][15] 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]

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.[16]

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.[10][17][18]

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.[10] 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.[10][13]

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.[19]

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)).[20][21][18][17][19][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.[17]

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.

The end of the HELP command output from RT-11SJ displayed on a VT100

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;[10] 4DOS and NDOS support the same feature by typing ? at the prompt[13] (which is also accepted by newer versions of DR-DOS COMMAND.COM); internal commands can be individually disabled or reenabled via SETDOS /I.[13] 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.[10]

Command description syntax[edit]

Built-in usage help and man pages commonly employ a small syntax to describe the valid command form:[22][23][24][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 (CLI) 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).[26][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.[27][28]

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:

  • The default VAX/VMS command shell, using the DCL language, has been ported to Windows systems at least three times, including PC-DCL and Acceler8 DCL Lite. Unix command shells have been ported to VMS and DOS/Windows 95 and Windows NT types of operating systems.
  • COMMAND.COM is the command-line interpreter of MS-DOS, IBM PC DOS, and clones such as DR-DOS, SISNE plus, PTS-DOS, ROM-DOS, and FreeDOS.
  • 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)
  • 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.
  • cmd.exe is part of the Windows NT stream of operating systems.
  • 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.
  • Windows users might use the CScript interface to alternate programs, from command-line. PowerShell provides a command-line interface, but its applets are not written in Shell script. Implementations of the Unix shell are also available as part of the POSIX sub-system,[29] 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
  • 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.
  • FreeBSD uses tcsh as its default interactive shell for the superuser, and ash as default scripting shell.
  • Many Linux distributions have the Bash implementation of the Unix shell.
  • Apple macOS and some Linux distributions use zsh. Previously, macOS used tcsh and Bash.
  • Embedded Linux (and other embedded Unix-like) devices often use the Ash implementation of the Unix shell, as part of Busybox.
  • Android uses the mksh shell,[30][31] which replaces a shell derived from ash[32] that was used in older Android versions, supplemented with commands from the separate toolbox[33] binary.
  • Routers with Cisco IOS,[34] Junos[35] 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.[36] 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.[37] An example of such a website is the CLI interface to DuckDuckGo.[38] There are also Web-based SSH applications, that allow to give access to server command line interface from a browser.

Many video games on the PC 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]

  • Comparison of command shells
  • List of command-line interpreters
  • Console application
  • Interpreter directive
  • Read-eval-print loop
  • Shell script
  • Run command
  • Graphical user interface § Comparison to other interfaces
  • In the Beginning… Was the Command Line

Notes[edit]

  1. ^ 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 (where n is the number of the page). Additionally, help for specific commands can be displayed by specifying the command name after ?, f.e. ?D will invoke help for the various dump commands (like D etc.). Some of these features were already supported by the DR DOS 3.41 SID86 and GEMSID.
  2. ^ 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.
  3. ^ With the exception of ASCII art.

References[edit]

  1. ^ «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.
  2. ^ a b «The Origin of the Shell». www.multicians.org. Retrieved 2017-04-12.
  3. ^ Metz, Cade (2013-01-03). «Say Bonjour to the Internet’s Long-Lost French Uncle». Wired. Retrieved 2017-07-31.
  4. ^ Mazières, David (Fall 2004). «MULTICS — The First Seven Years». Advanced Operating Systems. Stanford Computer Science Department. Retrieved 2017-08-01.
  5. ^ a b Jones, M. (2011-12-06). «Evolution of shells in Linux». developerWorks. IBM. Retrieved 2017-08-01.
  6. ^ «GNU BASH Reference».
  7. ^ «Microsoft Windows Command Shell Overview».
  8. ^ 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)
  9. ^ 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.)
  10. ^ 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.)
  11. ^ 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.
  12. ^ RISC OS 3 User Guide (PDF). Acorn Computers Limited. 1992-03-01. p. 125.
  13. ^ 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.
  14. ^ 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.
  15. ^ 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.
  16. ^ «Argument Syntax (The GNU C Library)». www.gnu.org. Retrieved 2021-07-09.
  17. ^ 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) […]
  18. ^ 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. […]
  19. ^ a b Paul, Matthias R.; Frinke, Axel C. (2006-01-16). FreeKEYB — Advanced international DOS keyboard and console driver (User Manual) (v7 preliminary ed.).
  20. ^ 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 ??.)
  21. ^ 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.
  22. ^ «The Open Group Base Specifications Issue 7, Chapter 12.1 Utility Argument Syntax». The Open Group. 2008. Retrieved 2013-04-07.man-pages(7) – Linux Conventions and Miscellany Manual (NB. Conventions for describing commands on Unix-like operating systems.)
  23. ^ «Command shell overview». Windows Server 2003 Product Help. Microsoft. 2005-01-21. Retrieved 2013-04-07.
  24. ^ «Command-Line Syntax Key». Windows Server 2008 R2 TechNet Library. Microsoft. 2010-01-25. Retrieved 2013-04-07.
  25. ^ Kernighan, Brian W.; Pike, Rob (1984). The UNIX Programming Environment. Englewood Cliffs: Prentice-Hall. ISBN 0-13-937699-2.
  26. ^ Pouzin, Louis. «The Origin of the Shell». Multicians.org. Retrieved 2013-09-22.
  27. ^ «Remembering Windows 95’s launch 15 years later». 2010-08-24.
  28. ^ «A history of Windows». windows.microsoft.com. Archived from the original on 2015-03-01.
  29. ^ «Windows POSIX shell compatibility».
  30. ^ «master — platform/external/mksh — Git at Google». android.googlesource.com. Retrieved 2018-03-18.
  31. ^ «Android adb shell — ash or ksh?». stackoverflow.com. Retrieved 2018-03-14.
  32. ^ «Android sh source». GitHub. Archived from the original on 2012-12-17.
  33. ^ «Android toolbox source». GitHub.
  34. ^ «Configuration Fundamentals Configuration Guide, Cisco IOS Release 15M&T». Cisco. 2013-10-30. Using the Command-Line Interface. The Cisco IOS command-line interface (CLI) is the primary user interface…
  35. ^ «Command-Line Interface Overview». www.juniper.net. Retrieved 2018-03-14.
  36. ^ «Google strange goodness».
  37. ^ jQuery Terminal Emulator
  38. ^ DuckDuckGo TTY

External links[edit]

  • The Roots of DOS David Hunter, Softalk for the IBM Personal Computer March 1983. Archived at Patersontech.com since 2000.
  • Command-Line Reference: Microsoft TechNet Database «Command-Line Reference»

A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and providing information to them as to what actions they are to perform. In some cases the invocation is conditional based on conditions established by the user or previous executables. Such access was first provided by computer terminals starting in the mid-1960s. This provided an interactive environment not available with punched cards or other input methods.

Today, many users rely upon graphical user interfaces and menu-driven interactions. However, some programming and maintenance tasks may not have a graphical user interface and use a command line.

Alternatives to the command-line interface include text-based user interface menus (for example, IBM AIX SMIT), keyboard shortcuts, and various desktop metaphors centered on the pointer (usually controlled with a mouse). Examples of this include the Microsoft Windows, DOS Shell, and Mouse Systems PowerPanel. Command-line interfaces are often implemented in terminal devices that are also capable of screen-oriented text-based user interfaces that use cursor addressing to place symbols on a display screen.

Programs with command-line interfaces are generally easier to automate via scripting.

Many software systems implement command-line interfaces for control and operation. This includes programming environments and utility programs.

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 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. 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’ can be any program that constitutes the user-interface, including fully graphically oriented ones. For example, the default Windows GUI is a shell program named EXPLORER.EXE, as defined in the SHELL=EXPLORER.EXE line in the WIN.INI configuration file. These programs are shells, but not CLIs.

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.[1] In 1964, MIT Computation Center staff member Louis Pouzin developed the RUNCOM tool for executing command scripts while allowing argument substitution.[2] 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.[3] Pouzin returned to his native France in 1965, and the first Multics shell was developed by Glenda Schroeder.[2]

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.[4][5] 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).[5]

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. 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. 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, 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. 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 interface[6][7] is:

Prompt command param1 param2 param3 … paramN
  • Prompt — generated by the program to provide context for the user.
  • Command — provided by the user. Commands are usually one of three classes:
    1. Internal commands are recognized and processed by the command line interpreter.
    2. Included commands run separate executables.
    3. External commands run executable files that may be included by other parties.
  • param1 …paramN — parameters provided by the user. The format and meaning of the parameters depends upon the command. In the case of Included or 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, 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 toFiles
  • doSomething how sourceFile destinationFile
  • doSomething how < inputFile > outputFile
  • doSomething 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.

CLI and resource protection[edit]

One can modify the set of available commands by modifying which paths appear in the PATH environment variable. Under Unix, 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. OS2MDOSE.EXE instead of OS2E.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 Windows CMD.EXE does this. 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]

Prompt of a BBC Micro after switch-on or hard reset

«Command prompt» redirects here. For the Windows component named Command Prompt, see cmd.exe.

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 $, %, #,[8][9] :, > or -[10] 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),[11] 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».[12] 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]

An MS-DOS command line, illustrating parsing into command and arguments

A command-line argument or parameter is an item of information provided to a program when it is started. 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:

«file.s» is a command-line argument which tells the program rm to remove the file «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. 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[10] 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», 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 beginning 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.
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 =; thus Prog -fFilename, Prog -f Filename, Prog -f:Filename, Prog -f=Filename.
  • Some programs allow single-character options to be combined;[10] others do not. The switch -fA may mean the same as -f -A,[10] 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.[13] 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.[10] Also, the current setting is reflected also in the built-in help screens.[10] 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.[14][15] 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]

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.[16]

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.[10][17][18]

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.[10] 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.[10][13]

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.[19]

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)).[20][21][18][17][19][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.[17]

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.

The end of the HELP command output from RT-11SJ displayed on a VT100

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;[10] 4DOS and NDOS support the same feature by typing ? at the prompt[13] (which is also accepted by newer versions of DR-DOS COMMAND.COM); internal commands can be individually disabled or reenabled via SETDOS /I.[13] 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.[10]

Command description syntax[edit]

Built-in usage help and man pages commonly employ a small syntax to describe the valid command form:[22][23][24][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 (CLI) 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).[26][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.[27][28]

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:

  • The default VAX/VMS command shell, using the DCL language, has been ported to Windows systems at least three times, including PC-DCL and Acceler8 DCL Lite. Unix command shells have been ported to VMS and DOS/Windows 95 and Windows NT types of operating systems.
  • COMMAND.COM is the command-line interpreter of MS-DOS, IBM PC DOS, and clones such as DR-DOS, SISNE plus, PTS-DOS, ROM-DOS, and FreeDOS.
  • 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)
  • 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.
  • cmd.exe is part of the Windows NT stream of operating systems.
  • 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.
  • Windows users might use the CScript interface to alternate programs, from command-line. PowerShell provides a command-line interface, but its applets are not written in Shell script. Implementations of the Unix shell are also available as part of the POSIX sub-system,[29] 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
  • 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.
  • FreeBSD uses tcsh as its default interactive shell for the superuser, and ash as default scripting shell.
  • Many Linux distributions have the Bash implementation of the Unix shell.
  • Apple macOS and some Linux distributions use zsh. Previously, macOS used tcsh and Bash.
  • Embedded Linux (and other embedded Unix-like) devices often use the Ash implementation of the Unix shell, as part of Busybox.
  • Android uses the mksh shell,[30][31] which replaces a shell derived from ash[32] that was used in older Android versions, supplemented with commands from the separate toolbox[33] binary.
  • Routers with Cisco IOS,[34] Junos[35] 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.[36] 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.[37] An example of such a website is the CLI interface to DuckDuckGo.[38] There are also Web-based SSH applications, that allow to give access to server command line interface from a browser.

Many video games on the PC 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]

  • Comparison of command shells
  • List of command-line interpreters
  • Console application
  • Interpreter directive
  • Read-eval-print loop
  • Shell script
  • Run command
  • Graphical user interface § Comparison to other interfaces
  • In the Beginning… Was the Command Line

Notes[edit]

  1. ^ 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 (where n is the number of the page). Additionally, help for specific commands can be displayed by specifying the command name after ?, f.e. ?D will invoke help for the various dump commands (like D etc.). Some of these features were already supported by the DR DOS 3.41 SID86 and GEMSID.
  2. ^ 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.
  3. ^ With the exception of ASCII art.

References[edit]

  1. ^ «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.
  2. ^ a b «The Origin of the Shell». www.multicians.org. Retrieved 2017-04-12.
  3. ^ Metz, Cade (2013-01-03). «Say Bonjour to the Internet’s Long-Lost French Uncle». Wired. Retrieved 2017-07-31.
  4. ^ Mazières, David (Fall 2004). «MULTICS — The First Seven Years». Advanced Operating Systems. Stanford Computer Science Department. Retrieved 2017-08-01.
  5. ^ a b Jones, M. (2011-12-06). «Evolution of shells in Linux». developerWorks. IBM. Retrieved 2017-08-01.
  6. ^ «GNU BASH Reference».
  7. ^ «Microsoft Windows Command Shell Overview».
  8. ^ 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)
  9. ^ 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.)
  10. ^ 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.)
  11. ^ 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.
  12. ^ RISC OS 3 User Guide (PDF). Acorn Computers Limited. 1992-03-01. p. 125.
  13. ^ 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.
  14. ^ 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.
  15. ^ 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.
  16. ^ «Argument Syntax (The GNU C Library)». www.gnu.org. Retrieved 2021-07-09.
  17. ^ 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) […]
  18. ^ 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. […]
  19. ^ a b Paul, Matthias R.; Frinke, Axel C. (2006-01-16). FreeKEYB — Advanced international DOS keyboard and console driver (User Manual) (v7 preliminary ed.).
  20. ^ 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 ??.)
  21. ^ 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.
  22. ^ «The Open Group Base Specifications Issue 7, Chapter 12.1 Utility Argument Syntax». The Open Group. 2008. Retrieved 2013-04-07.man-pages(7) – Linux Conventions and Miscellany Manual (NB. Conventions for describing commands on Unix-like operating systems.)
  23. ^ «Command shell overview». Windows Server 2003 Product Help. Microsoft. 2005-01-21. Retrieved 2013-04-07.
  24. ^ «Command-Line Syntax Key». Windows Server 2008 R2 TechNet Library. Microsoft. 2010-01-25. Retrieved 2013-04-07.
  25. ^ Kernighan, Brian W.; Pike, Rob (1984). The UNIX Programming Environment. Englewood Cliffs: Prentice-Hall. ISBN 0-13-937699-2.
  26. ^ Pouzin, Louis. «The Origin of the Shell». Multicians.org. Retrieved 2013-09-22.
  27. ^ «Remembering Windows 95’s launch 15 years later». 2010-08-24.
  28. ^ «A history of Windows». windows.microsoft.com. Archived from the original on 2015-03-01.
  29. ^ «Windows POSIX shell compatibility».
  30. ^ «master — platform/external/mksh — Git at Google». android.googlesource.com. Retrieved 2018-03-18.
  31. ^ «Android adb shell — ash or ksh?». stackoverflow.com. Retrieved 2018-03-14.
  32. ^ «Android sh source». GitHub. Archived from the original on 2012-12-17.
  33. ^ «Android toolbox source». GitHub.
  34. ^ «Configuration Fundamentals Configuration Guide, Cisco IOS Release 15M&T». Cisco. 2013-10-30. Using the Command-Line Interface. The Cisco IOS command-line interface (CLI) is the primary user interface…
  35. ^ «Command-Line Interface Overview». www.juniper.net. Retrieved 2018-03-14.
  36. ^ «Google strange goodness».
  37. ^ jQuery Terminal Emulator
  38. ^ DuckDuckGo TTY

External links[edit]

  • The Roots of DOS David Hunter, Softalk for the IBM Personal Computer March 1983. Archived at Patersontech.com since 2000.
  • Command-Line Reference: Microsoft TechNet Database «Command-Line Reference»

Аннотация: Описываются возможности языка командных файлов: работа с переменными и параметрами командной строки, реализация циклов, условных операторов и операторов перехода. Даются примеры обработки текстовых файлов с помощью командных файлов

Язык интерпретатора Cmd.exe. Командные файлы

Язык оболочки командной строки (shell language) в Windows реализован в виде командных (или пакетных) файлов. Командный файл в Windows — это обычный текстовый файл с расширением bat или cmd, в котором записаны допустимые команды операционной системы (как внешние, так и внутренние), а также некоторые дополнительные инструкции и ключевые слова, придающие командным файлам некоторое сходство с алгоритмическими языками программирования. Например, если записать в файл deltmp.bat следующие команды:

C:
CD %TEMP%
DEL /F *.tmp

и запустить его на выполнение (аналогично исполняемым файлам с расширением com или exe), то мы удалим все файлы во временной директории Windows. Таким образом, исполнение командного файла приводит к тому же результату, что и последовательный ввод записанных в нем команд. При этом не проводится никакой предварительной компиляции или проверки синтаксиса кода; если встречается строка с ошибочной командой, то она игнорируется. Очевидно, что если вам приходится часто выполнять одни и те же действия, то использование командных файлов может сэкономить много времени.

Вывод сообщений и дублирование команд

По умолчанию команды пакетного файла перед исполнением выводятся на экран, что выглядит не очень эстетично. С помощью команды ECHO OFF можно отключить дублирование команд, идущих после нее (сама команда ECHO OFF при этом все же дублируется). Например,

REM Следующие две команды будут дублироваться на экране …
DIR C:
ECHO OFF
REM А остальные уже не будут
DIR D:

Для восстановления режима дублирования используется команда ECHO ON. Кроме этого, можно отключить дублирование любой отдельной строки в командном файле, написав в начале этой строки символ @, например:

ECHO ON
REM Команда DIR C: дублируется на экране
DIR C:
REM А команда DIR D: — нет
@DIR D:

Таким образом, если поставить в самое начало файла команду

то это решит все проблемы с дублированием команд.

В пакетном файле можно выводить на экран строки с сообщениями. Делается это с помощью команды

Например,

Команда ECHO. (точка должна следовать
непосредственно за словом «ECHO»)
выводит на экран пустую строку. Например,

@ECHO OFF
ECHO Привет!
ECHO.
ECHO Пока!

Часто бывает удобно для просмотра сообщений, выводимых из пакетного файла, предварительно полностью очистить экран командой CLS.

Используя механизм перенаправления ввода/вывода (символы > и >>), можно направить сообщения, выводимые командой ECHO, в определенный текстовый файл. Например:

@ECHO OFF
ECHO Привет! > hi.txt
ECHO Пока! >> hi.txt

С помощью такого метода можно, скажем,
заполнять файлы-протоколы с отчетом о
произведенных действиях. Например:

@ECHO OFF
REM Попытка копирования
XCOPY C:PROGRAMS D:PROGRAMS /s
REM Добавление сообщения в файл report.txt в случае
REM удачного завершения копирования
IF NOT ERRORLEVEL 1 ECHO Успешное копирование >> report.txt

Использование параметров командной строки

При запуске пакетных файлов в командной строке можно указывать произвольное число параметров, значения которых можно использовать внутри файла. Это позволяет, например, применять один и тот же командный файл для выполнения команд с различными параметрами.

Для доступа из командного файла к параметрам командной строки применяются символы %0, %1, …, %9 или %*. При этом вместо %0 подставляется имя выполняемого пакетного файла, вместо %1, %2, …, %9 — значения первых девяти параметров командной строки соответственно, а вместо %* — все аргументы. Если в командной строке при вызове пакетного файла задано меньше девяти параметров, то «лишние» переменные из %1 – %9 замещаются пустыми строками. Рассмотрим следующий пример. Пусть имеется командный файл copier.bat следующего содержания:

@ECHO OFF
CLS
ECHO Файл %0 копирует каталог %1 в %2
XCOPY %1 %2 /S

Если запустить его из командной строки с двумя параметрами, например

copier.bat C:Programs D:Backup

то на экран выведется сообщение

Файл copier.bat копирует каталог C:Programs в D:Backup

и произойдет копирование каталога C:Programs со всеми его подкаталогами в D:Backup.

При необходимости можно использовать более девяти параметров командной строки. Это достигается с помощью команды SHIFT, которая изменяет значения замещаемых параметров с %0 по %9, копируя каждый параметр в предыдущий, то есть значение %1 копируется в %0, значение %2 – в %1 и т.д. Замещаемому параметру %9 присваивается значение параметра, следующего в командной строке за старым значением %9. Если же такой параметр не задан, то новое значение %9 — пустая строка.

Рассмотрим пример. Пусть командный файл my.bat вызван из командной строки следующим образом:

Тогда %0=my.bat, %1=p1, %2=p2, %3=p3, параметры %4 – %9 являются пустыми строками. После выполнения команды SHIFT значения замещаемых параметров изменятся следующим образом: %0=p1, %1=p2, %2=p3, параметры %3 – %9 – пустые строки.

При включении расширенной обработки команд SHIFT поддерживает ключ /n, задающий начало сдвига параметров с номера n, где n может быть числом от 0 до 9.

Например, в следующей команде:

параметр %2 заменяется на %3, %3 на %4 и т.д., а параметры %0 и %1 остаются без изменений.

Команда, обратная SHIFT (обратный сдвиг), отсутствует. После выполнения SHIFT уже нельзя восстановить параметр (%0), который был первым перед сдвигом. Если в командной строке задано больше десяти параметров, то команду SHIFT можно использовать несколько раз.

В командных файлах имеются некоторые возможности синтаксического анализа заменяемых параметров. Для параметра с номером n (%n) допустимы синтаксические конструкции (операторы), представленные в табл. 3.1.

Таблица
3.1.
Операторы для заменяемых параметров

Операторы Описание
%~Fn Переменная %n расширяется до полного имени файла
%~Dn Из переменной %n выделяется только имя диска
%~Pn Из переменной %n выделяется только путь к файлу
%~Nn Из переменной %n выделяется только имя файла
%~Xn Из переменной %n выделяется расширение имени файла
%~Sn Значение операторов N и X для переменной %n изменяется так, что они работают с кратким именем файла
%~$PATH:n Проводится поиск по каталогам, заданным в переменной среды PATH, и переменная %n заменяется на полное имя первого найденного файла. Если переменная PATH не определена или в результате поиска не найден ни один файл, эта конструкция заменяется на пустую строку. Естественно, здесь переменную PATH можно заменить на любое другое допустимое значение

Данные синтаксические конструкции можно объединять друг с другом, например:

%~DPn — из переменной %n выделяется имя диска и путь,

%~NXn — из переменной %n выделяется имя файла и расширение.

Рассмотрим следующий пример. Пусть мы находимся в каталоге C:TEXT и запускаем пакетный файл с параметром Рассказ.doc ( %1=Рассказ.doc ). Тогда применение операторов, описанных в табл. 3.1, к параметру %1 даст следующие результаты:

%~F1=C:TEXTРассказ.doc
%~D1=C:
%~P1=TEXT
%~N1=Рассказ
%~X1=.doc
%~DP1=C:TEXT
%~NX1=Рассказ.doc

Понравилась статья? Поделить с друзьями:
  • Какой язык использовался для написания операционной системы windows
  • Какую программу использовать для просмотра фото на windows 10
  • Какой формат ярлыков на рабочем столе windows 10
  • Какой язык вы хотите использовать для второй раскладки клавиатуры windows 10
  • Какую почтовую программу выбрать для windows 10