Windows terminal command line

Windows Terminal

Windows Terminal has revolutionized the command line experience on Windows. Gone are the days of the classic command prompt or the outdated CMD: users can now work with a more visually appealing, flexible, and powerful tool that combines different command interpreters under a single umbrella, allowing for customization and integration never before seen. Si Have you ever felt that working from the Windows console is tedious, limited, or outdated? Get ready to change your mind with this comprehensive and easy-to-follow guide.

In this article, you’ll delve into the world of Windows Terminal, exploring everything from the most basic concepts to the most advanced configurations. You’ll learn how to install it, configure it to your liking, take advantage of its lesser-known features and tricks, and how to get the most out of it whether you’re a beginner or experienced in development environments, scripting, or system administration. The command line will no longer seem like hostile territory, but will become a versatile and modern ally.

What is Windows Terminal and why do you need to know it?

Windows Terminal is a modern and flexible console application Designed to replace and improve the experience offered by the classic Command Prompt (CMD) and PowerShell, as well as integrating other shells like Bash (thanks to WSL, the Windows Subsystem for Linux). But what really differentiates it from previous terminals?

  • Multiple shells under one interface: You can access CMD, PowerShell, various WSL environments, Azure Cloud Shell, or any other command-line-based application using tabs and panels.
  • Advanced visual customization: Change colors, fonts, backgrounds (including images and GIFs), themes, and keyboard shortcuts.
  • Improved compatibility: Native support for Unicode and UTF-8, allowing international characters and emojis to be displayed correctly.
  • GPU-accelerated rendering engine: Text rendering is much smoother and faster, especially during heavy operations or when working with scripts that generate many lines.
  • Configuration via graphical interface and JSON files: Adapt it completely to your needs, either from its user interface or by editing the file settings. json.

Windows Terminal responds to the growing demand of advanced users and developers looking for modern and powerful tools to work in the command line, eliminating many of the limitations of the traditional CMD and the old PowerShell console itself.

Installation and Getting Started: How to Get Windows Terminal

Windows Terminal en Microsoft Store

Installing Windows Terminal is quick and easyMicrosoft itself recommends downloading it from the Microsoft Store to keep it always up to date, although there are also alternatives for advanced users:

  • You can install it from the Store by searching for ‘Windows Terminal’.
  • If you prefer the trial version or want to access new features earlier, install ‘Windows Terminal Preview’ with the command winget install Microsoft.WindowsTerminal.Preview from PowerShell.
  • If you use package management systems like Scoop o Chocolate and, you can install Terminal using its own commands.

Once installed, you can pin it to the taskbar to always have it handy. The first time you open it, you’ll notice the change: a modern interface, tabs at the top, and a much more pleasing and customizable visual design than the old black windows.

You can set Windows Terminal as your default terminal In Windows, all applications and shortcuts you invoke will automatically open this new console. To do this:

  1. Open the Terminal itself and access Configuration (gear icon or from the drop-down menu).
  2. In the section Home, choose ‘Windows Terminal’ as the default terminal application.

Remember that you can have both the stable and preview versions installed at the same time., and that both can coexist without problems.

General structure and first commands to avoid getting lost

When you start using Windows Terminal, you’ll encounter several familiar concepts and some key new features.:

  • Tabs and panels: Open multiple CMD, PowerShell, or WSL sessions simultaneously, in classic tabbed format (like browsers), or horizontally and vertically split panels.
  • Profiles: Each shell type (CMD, PowerShell, Ubuntu, etc.) has its own customizable profile in terms of color, icon, shortcut, and other parameters.
  • Quick setup: You can customize keyboard shortcuts, colors, and fonts from the settings menu or by editing the settings.json file.

From the first moment you can use the classic commands of each shell: for example, cd to change directory, dir o ls to list files, mkdir to create folders, del/rmdir/rm to delete files or folders, etc.

Helpful hint: Use the key tabulation to autocomplete file and folder names as you type commands, and the arrows up/down to scroll through the history of entered commands.

Profiles, Shells, and Configurations: Master the Flexibility of Windows Terminal

Windows Terminal PowerShell

One of the strengths of Windows Terminal is its ability to manage different profilesEach profile represents a different environment (CMD, PowerShell, Ubuntu, etc.), and you can customize them individually.

  • Different command line applications: Run PowerShell, Command Prompt, Azure Cloud Shell, or any WSL shell (such as Ubuntu, Debian, Fedora, etc.). You can even add custom shells, such as Oh-My-Zsh if you have WSL2 installed.
  • Creating and editing profiles: From the configuration menu, add a new profile by assigning your favorite shell or terminal executable to it, choose icons, and even modify the command that runs when you open it.

Profiles are automatically generated if you have multiple versions of PowerShell or WSL distributions installed. They will always appear listed in the graphical configuration interface and in the drop-down menu when you press the ‘+’ symbol to open new tabs.

Set the default profile: If you want, you can set which profile will open by default every time you start Windows Terminal, whether it’s PowerShell, CMD, or your favorite Linux distribution.

Dare to customize: Themes, colors, fonts and background images

Customization is one of the most powerful features of Windows Terminal. Forget boring white letters on a black background: here you can adjust virtually any visual aspect. Some of the most common and attractive customizations include:

  • Change color combinations: Choose from predefined schemes or create your own from the corresponding section of the settings menu or by editing settings.json.
  • Modify fonts and sizes: Choose modern monospaced fonts, adjusting font size and line height for better readability.
  • Add background images or GIFs: You can set static or animated images as backgrounds for your window or specific profiles, allowing you to further customize your workspace.
  • Adjust opacity and blur: Make your device translucent and choose the blur level for a more modern and pleasing look.

How do you change all this? The easiest way is to use the configuration interface. However, if you’re feeling adventurous, you can open the file settings. json (hold down the key) Shift while clicking on ‘Settings’) and directly edit the parameters for complete control.

Keyboard shortcuts, custom actions, and the command palette

Windows Terminal makes life much easier for the advanced user thanks to its editable keyboard shortcuts and powerful command palette..

  • Customizable shortcuts: Change the default shortcuts for copying, pasting, opening tabs or panels, closing sessions, switching between panels, toggling full-screen mode, and more.
  • For example, you can reassign the text copy of Ctrl + Shift + C to any shortcut you prefer (such as Ctrl + 1, for example), or opening new tabs, navigating between them (Ctrl + Tab, etc.).
  • Command palette: Summons the palette with Ctrl + Shift + P and quickly access many functions, internal commands, settings actions or search for specific commands.

Customization of actions is done from the corresponding section of the file settings. json or in the graphical menu, and allows you to define sequences of actions, shortcuts or even automated scripts to improve efficiency.

Command-line arguments and automation from Windows Terminal

Windows Terminal Ubuntu

One of the most advanced and useful aspects of Windows Terminal is its ability to be opened from the command line with custom arguments.This allows you to launch the terminal in predefined states, automatically open multiple tabs and panels with specific configurations, or start sessions in specific folders.

Some very useful examples:

  • wt -p "PowerShell" open a tab directly in PowerShell.
  • wt -p "Ubuntu" ; split-pane -H wsl.exe splits the window into two panes, one for Ubuntu and one for the default WSL shell.
  • wt --profile "Command Prompt" --startingDirectory "C:\Desarrollo" open CMD in the specified folder.

This feature is pure gold for those who want to automate everyday tasks., launching terminal suites and scripts that speed up your daily workflow. The available tools are numerous and well documented in the official help and on the Microsoft reference page.

Support for Unicode, UTF-8, and GPU-accelerated rendering

Windows Terminal’s compatibility with modern standards is one of its greatest added values. Thanks to its GPU-powered rendering engine, the visual experience is much smoother and text displays perfectly, even when we include:

  • International characters: Chinese, Japanese, Cyrillic… no problem.
  • Emojis and special symbols: Use them to customize your prompts or scripts.
  • 24-bit colors: Take advantage of the entire color range without limitations.

This makes the use of the terminal much more competitive compared to advanced terminals on UNIX or Linux systems, matching—or even surpassing—their graphical performance.

Tabs, panels, and multi-session management: Organize your console like never before

Do you work on multiple projects at once? Do you manage multiple servers? Do you develop in different environments? Nothing’s easier than opening multiple tabs or splitting your screen into horizontal or vertical panels to keep everything under control. Some advantages:

  • Parallel panels: Usa Alt+Shift+- for horizontal panels and Alt+Shift++ for verticals.
  • Independent tabs: Drag and drop tabs to create new windows or rearrange them.
  • Managing profiles in parallel: Run different shells, each in its own panel, and easily switch between them.

Visual management and flexibility are maximum., which is especially useful in development environments, network and server administration, as well as in testing or automation tasks.

How to edit settings from the interface and from the settings.json file

Más sobre la aplicación Windows Terminal

The Windows Terminal configuration is twofold: You can use an intuitive graphical interface or, if you are experienced, go deeper by directly editing the file. settings. json to achieve a total level of customization.

  • Configuration interface: Access it from the menu and navigate through the different sections to adjust profiles, colors, fonts, keyboard shortcuts, and more.
  • settings.json: hold down Shift when you open configuration and access the JSON in the path:
    • Stable version: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json
    • Preview Version: %LOCALAPPDATA%\Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json
    • Custom Installations (Scoop, Chocolately): %LOCALAPPDATA%\Microsoft\Windows Terminal\settings.json

From here you can adjust everything: add new profiles, modify themes, customize shortcuts, define complex actions, set default routes, and much more.

Troubleshooting and Help Resources

If you encounter problems with Windows Terminal, help is just a click away.:

  • You can check the Problem solving from the help menu within the Terminal itself.
  • If you detect a bug or need a new feature, access the repository from the ‘About’ menu. GitHub and report your issue directly to the development team.
  • The Microsoft Community and official forums are a great source of tips and solutions to common problems.

Feel free to explore the built-in help or use commands like Get-Help o wt --help to see the full list of available parameters and options.

Practical comparison with CMD and classic PowerShell

Windows Terminal marks a turning point compared to CMD and classic PowerShell, but what advantages does it really offer?

  • CMD: While it remains present and accessible as a profile within Terminal, it is limited in terms of customization, tab management, and support for modern standards.
  • Classic PowerShell: More powerful than CMD, but until the arrival of Terminal, it suffered from a basic visual design, without adequate support for Unicode or modern functionalities.
  • Windows Terminal: It unifies both worlds and adds Bash/WSL integration, improved graphical support, and a much more enjoyable experience for the modern user.

Comparison Example:

Function DCM PowerShell Windows Terminal
Tabs No No Yes
Boards No No Yes
Advanced customization No No Yes
Unicode and emojis No Limited Time Yes
GPU acceleration No No Yes
JSON Configuration No No Yes

Essential commands to get started with Windows Terminal

Whatever shell you use (CMD, PowerShell or Bash), Windows Terminal allows you to run all the classic commandsHere are some of the most useful and universal ones for moving and managing your files:

  • cd: Change the working directory.
  • dir o ls: List files and folders.
  • mkdir: Create new directories.
  • copy o cp: Copy files.
  • move o mv: Move files (or rename them).
  • of the, rm o rmdir: Delete files or folders.
  • type o cat: Displays the contents of a file.
  • exit: Close the terminal.
  • help o Get Help: Displays available help for commands.

In PowerShell, many commands have shorthand or Unix/Linux shell-inspired equivalents., making the transition from other systems much easier.

PowerShell in Windows Terminal: Getting Started and Helpful Tricks

PowerShell goes far beyond CMD and allows you to automate tasks and run complex scripts. With Windows Terminal, you can take advantage of all its features in a much more comfortable and enjoyable environment.

  • Quick access to commands: Usa Get-ChildItem (gci, ls) to list content, Set-Location (sl, cd) to navigate and New-Item (ni) to create files or folders.
  • Wildcards and auto-completion: Use ‘*’, ‘?’, and the Tab key to work with multiple files at once or speed up typing long filenames.
  • Copy and rename files: Copy-Item (cp) and Move-Item (mv) are essential commands for file management.
  • Delete real files: Eye with Remove-Item (rm) because it permanently deletes files and folders, without going through the trash.
  • Redirect output: Usa > to overwrite files and >> to add content.
  • Find text: Select-String (sls, equivalent to grep on Linux) allows you to search for text strings in multiple files simultaneously.

PowerShell also allows you to pipe the output of one command to another. using the operator |, allowing you to build complex and efficient workflows.

Essential diagnostic and administrative commands in Windows Terminal

Windows Terminal is the ideal tool for running diagnostic and system administration commands.Here are some very useful examples, especially for troubleshooting, networking, and advanced management:

  • SYSTEMINFO: Displays detailed system information (CPU, RAM, motherboard, etc.).
  • CHKDSK: Scans and repairs disk drives.
  • IPCONFIG: Displays network information, IP, subnet mask, etc.
  • NETSTAT: Displays active network connections and open ports.
  • TRACERT: Analyzes the route followed to connect to an address.
  • GETMAC: Displays the MAC address of the network card.
  • DRIVERQUERY: List all installed drivers.
  • TASKLIST / TASKKILL: Displays active processes and allows you to terminate them from the terminal.
  • CLEANMGR: Launch Disk Cleanup.
  • SHUTDOWN: Allows you to shut down or restart your computer from the command line.

Using these commands from Windows Terminal is much more convenient thanks to auto-completion, easy copy and paste, and the ability to manage multiple simultaneous sessions.

File and Directory Management: Tips, Shortcuts, and Best Practices

Working with files from Windows Terminal is faster and more efficient if you master certain tricks and shortcuts:

  • Relative and absolute paths: Usa ./ y ../ to refer to the current directory and the parent directory, respectively.
  • Moving between disks: Change unit by simply entering its letter (e.g. D:).
  • Wildcards to manage multiple files: Use ‘*’ to select all files of a type (for example copy *.txt E:\backup).
  • Autocomplete: Take advantage of the Tab key in both PowerShell and CMD.
  • Up/down arrows: Recalls previously typed commands without having to retype them.
  • Avoid spaces in file names or use quotes: If the file or folder contains spaces, enclose them in quotes or use auto-completion to avoid errors.

Remember that some actions, such as deleting files with rm o del, are irreversible, so it is always advisable to check the names carefully before executing them.

Integrating external tools and scripts: The power of automation

Pestañas de Windows Terminal

One of the biggest attractions of Windows Terminal is the ability to integrate with external tools and scriptsYou can run Python scripts, manage Git, work with development tools, or launch programs from the terminal, all in a single environment.

  • Python and other languages: Make sure you have set up the PATH correctly to run Python, Ruby, Node.js, etc. scripts directly from the terminal.
  • Run external programs: Type the name of the executable or script and press Enter.
  • Automate processes: Group commands into .bat, .ps1 (PowerShell), or .sh (Bash in WSL) files for recurring tasks.
  • Install and use tools like Chocolatey, Scoop or Winget: Improves the management of programs and scripts in an automated manner.

Use aliases in PowerShell to shorten common commands, thus speeding up your daily workflow.

Exercises and best practices to master Windows Terminal

There is no better way to learn than by practicing.Here are some challenges and routines to help you strengthen and improve your skills in the modern Windows terminal:

  • Deletes all files that begin with a specific pattern using wildcards and the appropriate command (del HelloWo* o rm HelloWo*).
  • Try copying and pasting long entries and outputs to manage errors or system messages.
  • Experiment with input/output redirection to save the output of commands to files, concatenate content, or combine output using pipes (|).
  • Explore the help for each command and expand your knowledge of advanced parameters (Get-Help o man ).
  • Configure your terminal visually to your liking and experiment with different color schemes, background images, and shortcuts.

The more you use Windows Terminal, the more you’ll discover its potential and ability to save time on your everyday tasks.

Comparison table of key commands in Windows Terminal (CMD, PowerShell, Bash)

Command (Windows) Command (Mac/Linux) Functionality Example
exit exit Close the terminal exit
cd cd change directory project cd
dir ls List files and folders dir
copy cp Copy files copy file.txt D:\backup\
move mv Move or rename files move file.txt to D:\backup\
mkdir mkdir Create directories mkdir newscript
del / rmdir rm / rm -r Delete files/folders del viejo.txt / rmdir temp
/? Mon Get help cd /? / man cd

Quick references for PowerShell and Bash equivalents

Cmdlet Alias Bash Description
Get-ChildItem gci ls List directories/files
Set-Location sl cd Change directory
New-Item ni touch Create a new file/directory
remove-item rm rm Delete files/folders permanently
Move Item mv mv Move or rename files
Copy Item cp cp Copy files
Write-Output write threw out Print text or redirect to file
Get-Content gc cat Reads the contents of files
Select-String sls grep Search for text in files
Measure-Object measure wc Count lines, words or characters
> / >> > / >> Redirects output to file
| | Pipes to concatenate commands
Get Help Mon Displays help for a command
exit exit Exit terminal

With Windows Terminal, the command line in Windows finally reaches the level of productivity, customization, and power that users have been waiting for years.. It’s no longer just a tool for advanced administrators or developers: it’s perfectly accessible for those who want to take things a step further and master their system. Thanks to its open ecosystem, integration with WSL and other shells, customizable visual appearance, and the ability to adapt every detail to our workflow, Windows Terminal has become the nerve center of Windows productivity. Explore it, lose your fear of experimenting and get the most out of it: few tools will give you back so much for every minute you invest in learning how to use them..

The new Windows terminal app is now available in the Microsoft Store which means anyone can try it out. You no longer have to compile it from its source on Github. The new Windows terminal app supports multiple command lines but out-of-the-box, it only has PowerShell and Command Prompt added to it. Here’s how you can add a command line to the new Windows terminal app.

Windows Terminal settings

Install the Terminal app from the Microsoft Store. Click the little dropdown arrow next to the plus/new tab button and select Settings. This is going to open a file called Profiles.json. In order to add a command line to the new Windows Terminal app, you have to edit this file. Before you edit it though, copy everything in the file, and paste it into a new Notepad file. Save it with the name Profiles and the JSON extension somewhere you know it won’t be deleted by accident. This file is basically a back up of the original settings.

JSON editor

You will need a JSON editor to edit the Profiles.json file. You can use Notepad however, it’s probably a good idea to use Notepad++ which is free but can format the file much better.

JSON syntax

Editing the Profiles.json file is easy however, if you’re unfamiliar with the JSON syntax, you need to know a few important things before you dive in;

  1. Do not use a backslash (\) in file paths. You must replace them with a forward slash (/).
  2. Always close file paths in double quotes.
  3. All lines must end with a comma EXCEPT for the last line in a section or block.
  4. A section in the Profiles.json file starts with its name declared within double-quotes. We will be editing the Profiles section (see screenshot below).

Add Profile

Scroll to the end of the “Profiles”: section, and paste the following there. You will need to edit it before you can save the settings.

{
"acrylicOpacity" : 0.5,
"background" : "#012456",
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "powershell.exe",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 20,
"guid" : "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"historySize" : 9001,
"icon" : "ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png",
"name" : "Windows PowerShell",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : false
},

The lines you need to edit are;

  • “commandline”
  • “guid”
  • “icon”
  • “name”

Go to the following location and open the Profiles.json file with your preferred editor.

%USERPROFILE%\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState

Remember that if this is the last profile within the profile section, you must remove the comma at the very end. If you plan on adding another profile below this one, leave the comma there but make sure the last profile doesn’t have a comma outside the curly brace.

In the “commandline” line, give the complete path to the EXE of the command line you want to add. If you’ve enabled Windows Subsystem for Linus, you can simple add “bash.exe” here.

In the “guid” line, you need to generate a new GUID and enter it there however, if you’re adding Ubunut’s bash, scroll down the relevant section below and use the GUID and icon path provided there. They’re present by default in the ProfileIcons folder.

For the “icon” line, give the  complete path to the icon file you want to use. The file must be a PNG file. The icon will appear in the menu next to the name of the command line it is for.

In the “name” line, enter the name of the command line e.g., Bash, Linux, or Python. Save the changes and you’re good to go.

Add Linux Bash to Windows Terminal

To add Linux Bash to Windows Terminal, enter the following Profile without making any changes to it.

{
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "bash.exe",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 10,
"guid" : "{9acb9455-ca41-5af7-950f-6bca1bc9722f}",
"historySize" : 9001,
"icon" : "ms-appx:///ProfileIcons/{9acb9455-ca41-5af7-950f-6bca1bc9722f}.scale-100.png",
"name" : "Linux Bash Shell",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : true
}

In order to add Python to the new Windows Terminal app, use the following profile. You can change the GUID to something else if you want but it isn’t necessary. You must have Python installed on your system. You can get it here. You will need to edit the path in the “icon” line and change it to whichever file you want to use for the icon.

{
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "py.exe",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 10,
"guid" : "{1850e97f-16dc-4281-9ea9-0100c4e852c5}",
"historySize" : 9001,
"icon" : "C:/Users/YourUserName/AppData/Local/Programs/Python/Python37/Lib/test/imghdrdata/python.png",
"name" : "Python",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : true
}

Save the changes made to Profiles.json and the Windows Terminal app will show the new command line(s) that you’ve added.

default avatar image

Fatima Wahab

Fatima has been writing for AddictiveTips for six years. She began as a junior writer and has been working as the Editor in Chief since 2014.

Fatima gets an adrenaline rush from figuring out how technology works, and how to manipulate it. A well-designed app, something that solves a common everyday problem and looks

The Command Prompt (CMD) utility built into Windows OS is run with commands. This utility helps you to troubleshoot and fix most issues with the OS. It is quite easy to use if you know the commands and their functions. Basically, there are over 200 Windows terminal commands (yes, the command prompt interface is also called “Terminal”).

Well, most of the commands are for experienced developers that understand the depth of Windows OS. This article lists the most common ones you’re likely to use quite frequently for troubleshooting, file copying, or accessing files over a network. More so, to run these commands successfully, you need to use an admin account on the computer.

On a quick note, if you want to view all the CMD commands, launch the CMD terminal, type “help” and press the Enter key. Meanwhile, here are the commands and their function.

Append
Open files in another directory

Arp
Display or change entries in the ARP cache

Assoc
Display or change file type

At
Schedule commands

Atmadm
Display Asynchronous Transfer Mode (ATM) connections

Attrib
Change file attributes

Auditpol
Display or change audit policies.

Bcdboot
Copy boot files to system partition and create new system BCD store

Bcdedit
View or edit Boot Configuration Data

Bdehdcfg
Prepare a hard drive for BitLocker Drive Encryption

Bitsadmin
Create, manage, and monitor jobs

Bootcfg
Build, modify, or view the boot.ini file

Bootsect
Configure the dows 10 and Windows 8.

Call
Run scripts or batch programs from another script

Certreq
For performing different certification authority (CA) certificate functions

Certutil
Dump and display CA configuration information

Chcp
Display or configure the active code page number

Chdir
Display the drive letter and folder you’re currently in

Checknetisolation
For testing network apps

Chglogon
Enables, disables, or drains terminal server session logins

Chgport
Display and change COM port mappings

Chgusr
Change installation mode of terminal servers

Chkdsk
Check disk command for troubleshooting hard disk issues

Chkntfs
Configure or display disk drive boot

Cipher
Print or changes encryption status for files/folders on NTFS partitions

Clip
Send command results to Windows clipboard

Cls
Clears all previous commands in the terminal

Cmd
Starts the command prompt terminals

Cmdkey
Display, create, and remove saved usernames and passwords

Comp
For comparing two files

Compact
Display of edit compression state of files on NTFS partitions

Convert
Convert FAT or FAT32 to the NTFS format

Copy
Copy files

Cscript
Run scripts via Microsoft Script Host

Ctty
Change input and output devices

Date
Show the date

Debug
To test and edit programs

Defrag
Defragment a drive

Del
Delete files

Deltree
Delete a directory and all files in it

Diantz
Losslessly compress file

Dir
Display the directory you’re in

Diskcomp
Compare floppy disks

Diskcopy
Copy floppy disks

Diskpart
Create, manage, and delete partitions

Diskraid
Manage and configure RAID arrays

Driverquery
Display all installed drivers

Echo
Show messages from within a script or batch file

Edit
Start the MS-DOS Editor

Erase
File deletion

Exit
Close the CMD terminal

Forcedos
Start program in the MS-DOS subsystem

Format
Format a drive

Ftp
Transfer files via FTP

Getmac
Display MAC address of all the network controllers

Gpresult
Display Group Policy settings

Gpupdate
Update Group Policy settings

Hostname
Name of the current host

Hwrcomp
Compile custom dictionaries for handwriting recognition

Hwrreg
Install previously compiled dictionaries

Icacls
Display or change access control lists of files

Ipconfig
Show your network IP information

Irftp
Transmit files via an infrared link

Ktmutil
Starts the Kernel Transaction Manager utility

Licensingdiag
Generate text-based log

Loadhigh (LH)
Load programs in high memory

Lock
Lock a drive

Logman
Create and manage Event Trace Session and Performance logs

Logoff
Terminate a session

Mem
Shows free and used memory info

Mkdir
Create a new folder

Mount
Mount Network File System (NFS) network shares

Move
Move files

Msg
Send message to a user

Nbtstat
Show TCP/IP information of a remote PC

Net
Display network settings and information

Netsh
Start Network Shell

Nfsadmin
Manage servers or clients for NFS

Path
Display the path of an executable file

Ping
Sends an Internet Control Message Protocol (ICMP) Echo Request message

Pkgmgr
Start Windows Package Manager

Print
Print texts

Qappsrv
Display Remote Desktop Session Host servers

Qbasic
Starts QBasic

Qprocess
Display information of running processes

Rdpsign
Sign a Remote Desktop Protocol (RDP) file

Reagentc
Configure Windows Recovery Environment (RE)

Reset
Reset sessions

Robocopy
Run the robocopy utility

Sc
Configure services

Sfc
System File Checker – used to troubleshoot issues with hard drives

Shutdown
Log off or shut down a computer

Systeminfo
Print all basic Windows configuration information

Takeown
Regain access to files an administrator was denied access to

Tasklist
Show all ongoing applications, services, and their Process ID (PID)

Time
Show current time

Tree
Graphically display folder structures

Umount
Remove Network File System (NFS) mounted network shares

Vol
Show the volume and serial number of a disk

Winmgmt
Starts the CLI version of WMI

Winrm
Start Windows Remote Management

These are the commonest commands you need to know. They are all executable from the command prompt terminal.

Using the command line to perform certain actions has long seemed complicated. But for more advanced users, such as system administrators, using it is an advantage. With it, they can more easily manage the operation of some system components. Or access information that cannot be accessed from the system’s graphical interface. The Windows console makes it possible. We have been living in the era of graphical interfaces for decades. Therefore, some may think that the Windows console has disappeared from the operating system. But this is not the case, and it is still present. In this way, we enhance the performance of some tasks. Even, Microsoft has decided to renew it a little in Windows 11. That yes, maintaining its essence and with the commands that make that it continues being important for many users. Today we will know some aspects and commands of Windows Terminal.

The default Windows 11 console: Windows Terminal

The arrival of Windows 11 has brought with it a renewal that has taken quite a few users surprised. Nothing more and nothing less than the establishment of Windows Terminal as command line and console by default of Windows 11. Let us remember that this comes after its incorporation to Windows 10. We are talking about the system command line application.

Windows Terminal was introduced a few years ago. Specifically, at the Build 2019 event. In addition, from the beginning it has had a clear function: to serve as a command line tool, but renewed. Not in vain, its development was outside the Windows work team. In addition, its code was released, and free. All wrapped in a very recognizable air of Linux, a system that Windows is getting closer and closer to.

Increased benefits

This tool is more powerful than the command line of previous versions. In fact, it can manage the basic command console present on the computer since Windows NT. But it also runs the more advanced PowerShell console, available since Windows Vista. With the latter, in addition to using the command prompt, it is possible to create commands and combine them through sequences. However, to do so, you need to have some programming skills. Specifically, in C#.

In addition, you can have additional tabs for other tools open at the same time. This is the case of WSL 2, the second version of a Linux subsystem for Microsoft Windows. Its mission is to run Linux distributions. In addition to applications created for this system, within Windows itself. In short, Windows Terminal already works as a unifying tool for the different Windows command lines and consoles. However, this does not mean that it has eliminated the other two Windows command line applications installed on the system: CMD (or command line) and PowerShell.

Access to the command console in Windows 11

There are several ways to access the console through the command prompt. To use one of the fastest ones, the first thing you have to do is to open the Windows Finder, and type in it CMD. Before it opens, note that you can choose whether you want it to run in user mode or administrator mode. In the first case, you will be able to use it with various limitations. However, in exchange, there will be fewer unforeseen events if the user is not very experienced or is not interested in having access to various resources and options. You can also access through the Run tool, through the Finder in the Start menu.

PowerShell can also be accessed through the Windows Finder. But in this case, what you have to type in it is PowerShell. As for the Windows Terminal, until this version 11 it was not installed by default. Therefore, it was necessary to download that tool from its Microsoft Store page, and install it afterwards.

If you have this tool installed, or if you are using Windows 11, you only need to access it. Remember that you will be able to access, in different tabs, to PowerShell or to the command line. And it’s opening in Windows 11 is as simple as selecting the corresponding option in the contextual menu that appears when clicking with the right button of the mouse.

The main Windows terminal commands

It doesn’t matter which application or tool you use to access the command line. In text mode, in any of them you will have to use the same commands as in previous versions. Just as if you were using the old MS-DOS, but with slight differences. For example, you have :customization possibilities (although small), some colors and even tabs in the case of Windows Terminal.

To use any command, you only have to type it, followed by its modifiers in case it supports them, and you need them, and press the Enter key. The results of applying the command will be practically immediate. Below you have a list of the most useful commands for the Windows command line are the following:

Another Windows terminal commands

  • Chkdsk: Checks what state a given disk drive is in. Either a disk partition or a volume. It also generates, and displays on screen, a report of how the examined drive or partition is. In addition to this, it can correct some errors that the disk may present. In the case of locating damaged sectors on it, it can even recover the information they contain.
  • Systeminfo: This command is also responsible for displaying information, but in this case, about the entire operating system. It displays information about the computer’s processor, the RAM used and available, the BIOS, the virtual memory used and available, and who manufactured the motherboard. Furthermore, what version of the system is installed, as well as what updates it has.
  • Dir: Returns a list of the files and subdirectories in a directory. To move from one directory to another, use the CD command, with the appropriate modifier.
  • Del: Deletes one or more files from the folder, even if the file does not allow deletion when using the Windows GUI to try to delete it.
  • Diskpart: Disk drive management, internal or external. It has disk management functions, both whole disks and partitions. Even works for virtual disks.
  • Format: Formats a disk drive and prepares it to install Windows.
  • Help: Displays a list of all the commands that can be used in the console. It can also be used to learn details about the operation of a command, if used with Help + command name.

Continuation of the list

  • IPconfig: Its mission is to provide information about the TCO/IP network configuration values at the time the query is made. It also updates the DNS and DHCP settings.
  • Ping: Checks that there is communication between the local computer and a remote computer on an IP network (or with several). It is also used to check the status and quality of a network, as well as its transmission speed.
  • Netstat – Provides information about the network, as well as the opportunity to perform analysis and diagnostics of its status. It is also used to find out which IP address is behind a domain name.
  • Nslookup: This command is used to know, in case of a connection problem, if a DNS is resolving properly both IPs and names. It also returns the list of incoming and outgoing connections to a computer.
  • Tracert: With this command you can find out which packets are coming from a point in a network, as well as their latency, among other information.

These are certainly not the only commands you can use. However, perhaps the most used and the most useful for users of a Windows system with some experience using the Windows console. However, if you want to know the rest, as we have mentioned, you only have to resort to the Help command for further information. In this way, we have seen the main Windows Terminal commands. See you later!

— Advertisement —

Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.

Subscribe

«The best Linux newsletter on the web»

Работа с терминалом может пугать тех, кто привык работать с графическими пользовательскими интерфейсами (GUI). Тем не менее, это важный инструмент, к работе с которым разработчику Python нужно привыкнуть. И как только вы улучшите свои навыки по работе с терминалом, он станет чрезвычайно мощным инструментом в вашем арсенале. С помощью всего нескольких команд в терминале вы можете выполнять задачи, которые невозможно или, по крайней мере, очень утомительно выполнять в графическом интерфейсе.

В этом уроке вы узнаете, как:

  • Найти терминал в операционной системе
  • Открыть терминал
  • Осуществить навигацию по файловой системе с помощью основных команд
  • Создать файлы и папки с помощью терминала
  • Управлять пакетами с помощью pip-команд
  • Отслеживать файлы с помощью Git в терминале

Если вы новичок в работе с терминалом или хотите расширить свое понимание его возможностей, то это руководство станет отличным стартом. В нем вы познакомитесь с некоторыми основными командами и узнаете, как использовать pip и Git для управления проектами в терминале.

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

Установите и откройте терминал

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

Примечание

Есть еще два других термина, которые время от времени используются в сочетании с терминалом:

  1. Оболочка — это программа, с которой вы взаимодействуете при выполнении команд в терминале.
  2. Интерфейс командной строки (CLI) — это программа, предназначенная для запуска в оболочке внутри терминала.

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

Если вы используете компьютер с Linux или macOS, то терминал уже встроен. Вы можете начать использовать его прямо сейчас.

В Windows у вас также есть доступ к приложениям командной строки, таким как Command Prompt. Однако при работе с данным руководством и работы с терминалом в целом вместо этого следует использовать приложение терминала Windows.

Далее вы узнаете, как установить и открыть терминал в Windows и как найти терминал в Linux и macOS.

Терминал Windows — это современное и многофункциональное приложение, которое дает вам доступ к командной строке, нескольким оболочкам и расширенным параметрам настройки. Если у вас Windows 11 или выше, есть вероятность, что терминал Windows уже присутствует на вашем компьютере. В противном случае вы можете скачать приложение из Microsoft Store или из официального репозитория GitHub.

Прежде чем продолжить работу с этим учебным пособием, вам необходимо настроить терминал на вашем компьютере с Windows. Вы можете ознакомиться с документом «Your Python Coding Environment on Windows: Setup Guide», чтобы узнать, как установить терминал Windows.

После установки терминала Windows вы найдете его в меню «Пуск» в разделе Terminal. При запуске приложения вы должны увидеть окно, которое выглядит следующим образом:

⌨️ Терминал для начинающих: полезные команды для работы в командной строке Windows, Linux и MacOS

Данное изображение и все последующие взяты отсюда.

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

Linux

Вы можете найти терминальное приложение в меню приложений вашего дистрибутива Linux. Кроме того, вы можете нажать Ctrl+ Alt + T на клавиатуре или использовать панель запуска приложений и выполнить поиск по слову Terminal.

После открытия терминала вы должны увидеть нечто похожее:

⌨️ Терминал для начинающих: полезные команды для работы в командной строке Windows, Linux и MacOS

То, как вы открываете терминал, также может зависеть от того, какой дистрибутив Linux вы используете.

macOS

Обычный способ открыть приложение терминала в macOS — открыть Spotlight Search и выполнить поиск Terminal. Вы также можете найти приложение терминала в папке приложения внутри Finder.

Когда вы открываете терминал, вы видите окно, похожее на изображение ниже:

⌨️ Терминал для начинающих: полезные команды для работы в командной строке Windows, Linux и MacOS

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

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

Изучите основные команды терминала

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

В зависимости от вашей операционной системы вы будете запускать команды терминала в определенной оболочке. Для Linux это, скорее всего, Bash, для более новых версий macOS — Zsh , а для Windows — PowerShell. Эти оболочки различаются по своим функциям, но у них общие основные команды.

Примечание

Вы можете думать о командах как о небольших программах, которые встроены в вашу оболочку или могут быть добавлены внешними приложениями. В PowerShell команды также называются cmdlets.

В этом разделе вы познакомитесь с наиболее часто используемыми командами терминала. Чтобы ознакомиться с ними, выберите свою операционную систему в переключателе платформ ниже:

Вот команды Windows, которые вы рассмотрите:

⌨️ Терминал для начинающих: полезные команды для работы в командной строке Windows, Linux и MacOS

Linux + macOS:

⌨️ Терминал для начинающих: полезные команды для работы в командной строке Windows, Linux и MacOS

Слова, написанные прописными буквами, являются ссылками на аргументы, допускаемые командами.

Далее вы узнаете, как перемещаться по файловой системе, а также создавать, редактировать и удалять файлы и каталоги. К концу этого раздела у вас будет прочная база для работы с терминалом и вы сможете уверенно выполнять многие повседневные задачи. Вы можете сохранить этот настрой и с его помощью решать другие задачи в терминале, такие как использование pip, взаимодействие с Git и создание интерфейсов командной строки с помощью Python.

Навигация по вашей файловой системе

Файловая система — это иерархическая структура каталогов и файлов на компьютере. Обычно это то, что вы видите, когда открываете приложение файловой системы с графическим интерфейсом, такое как проводник Windows или Finder в macOS. Это также отличное место для начала вашего путешествия по терминалу, но опять же, вы просто знакомитесь со всеми возможностями терминала.

Папка, которую вы сейчас открыли в файловой системе, является текущим рабочим каталогом (current working directory, cwd). Как вы заметите, вы используете рабочий каталог в качестве точки отсчета для многих операций с файловой системой. Понимание устройства файловой системы и текущего рабочего каталога важно для эффективной навигации и управления файлами и каталогами в терминале.

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

Чтобы начать работу, узнайте свой текущий рабочий каталог:

        $ pwd
/Users/realpython
    

Команда pwd (расшифровывается как print working directory) используется для определения вашего текущего местоположения в файловой системе. Здесь pwd показывает, что текущим рабочим каталогом является /Users/realpython.

Рабочий каталог — это текущий каталог, в котором вы работаете. Здесь по умолчанию будут выполняться команды.

Подробнее о текущем рабочем каталоге

Есть два термина, которые стоит изучить в контексте текущего рабочего каталога:

  1. Переменные среды
  2. PATH (путь)

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

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

Windows

        PS> (cat ENV:Path) -Split ";"

    

Linux + macOS

        $ echo "${PATH//:/\n}"

    

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

Чтобы увидеть, какие файлы и папки содержатся в директории /Users/realpython, вы можете использовать ls (сокращение от list):

        $ ls
Applications          Movies
Desktop               Music
Documents             Pictures
Downloads             Public
Library
    

Если вы введете ls и нажмете на Enter, вы увидите список всех элементов в текущем рабочем каталоге. В этом случае в примере показаны папки, которые вы, скорее всего, найдете в пользовательском каталоге на компьютере с macOS.

Вы также можете использовать флаг -a с командой ls, которая являет сокращением от all. Флаг -a покажет вам все элементы в текущем рабочем каталоге, включая скрытые элементы.

Другой флаг, который вы можете использовать, это -l, сокращение от long. Когда вы используете этот флаг вместе с ls, команда показывает вам подробную информацию об элементах в текущем рабочем каталоге.

Вы также можете комбинировать эти флаги, чтобы показать подробную информацию обо всех элементах, включая скрытые, с помощью ls -al:

        $ ls -al
total 80
drwxr-xr-x+  25 realpython  staff    800 Nov 26 11:51 .
drwxr-xr-x    6 root        admin    192 Nov  7 13:22 ..
-rw-r--r--@   1 realpython  staff  14340 Nov  7 16:04 .DS_Store
drwx------  134 realpython  staff   4288 Nov  8 18:37 .Trash
drwx------@   3 realpython  staff     96 Dec  3  2021 Applications
drwx------@  22 realpython  staff    704 Nov  7 16:00 Desktop
drwx------+   4 realpython  staff    128 Nov 17  2021 Documents
drwx------+   3 realpython  staff     96 Nov  1  2021 Downloads
drwx------@  86 realpython  staff   2752 Nov  7 21:08 Library
drwx------    6 realpython  staff    192 Jul 12 14:53 Movies
drwx------+   4 realpython  staff    128 Nov 26  2021 Music
drwx------+   4 realpython  staff    128 Nov  1  2021 Pictures
drwxr-xr-x+   4 realpython  staff    128 Nov  1  2021 Public
    

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

Примечание

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

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

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

        drwx------@  22 realpython  staff    704 Nov  7 16:00 Desktop

    

Эта строка дает вам ценную информацию об элементе. Там есть каталог с именем Desktop. Дата последнего изменения — 7 ноября в 16:00, размер — 704 байта.

Кроме того, вы можете увидеть информацию о правах владельца и группы. Если вы хотите узнать больше о нотации разрешений файловой системы, вы можете ознакомиться с notation of traditional Unix permissions.

Каждая папка в выводе ls представляет собой подпапку внутри вашего текущего рабочего каталога. Чтобы изменить текущий рабочий каталог на Desktop/подпапку, используйте команду cd от change directory (смена директории):

        $ pwd
/Users/realpython
$ cd Desktop
$ pwd
/Users/realpython/Desktop
    

Когда вы сначала вводите cd, а затем имя каталога, текущий рабочий каталог будет изменен на указанный. После запуска команды cd Desktop текущий рабочий каталог изменится на /Users/realpython/Desktop.

Обратите внимание, что вы не указываете слеш / или индикатор диска, как C:\, в начале Desktop. Вызов такого пути указывает на то, что вы хотите перейти по пути, относящемуся к каталогу, в котором вы сейчас находитесь.

Вы использовали относительный путь в приведенной выше команде для перехода во вложенную папку. Относительные пути упрощают обращение к элементам в вашей файловой системе, поскольку вам не нужно указывать полный путь от корневого каталога. При этом вы также можете перейти в любой каталог вашей файловой системы, используя полный или абсолютный путь:

  • Windows
        PS> cd C:\Users\realpython\Desktop
PS> pwd
C:\Users\realpython\Desktop
    

В этом случае cd команда изменяет текущий рабочий каталог на каталог C:\Users\realpython\Desktop, независимо от его предыдущего местоположения.

  • Linux + macOS
        $ cd /Users/realpython/Desktop
$ pwd
/Users/realpython/Desktop
    

В этом случае cd команда изменяет текущий рабочий каталог на каталог /Users/realpython/Desktop, независимо от его предыдущего местоположения.

Если вы используете для команды cd несуществующий путь, терминал выдаст ошибку. Вскоре вы узнаете, как создавать новые каталоги. Перед этим сделайте заключительное действие в вашей файловой системе.

Чтобы переместиться на один каталог вверх, вы обычно используете не имя родительской папки, а две точки:

        $ cd ..
$ pwd
/Users/realpython
    

Две точки ( ..) представляют родительский каталог текущего каталога. Использование cd ..перемещает вас на один каталог вверх в иерархии файловой системы.

В приложении файловой системы с графическим интерфейсом, таком как Windows Explorer или macOS Finder, вы должны щелкать маленькие значки папок курсором мыши. В терминальном приложении вы используете команды для выполнения задач — например, cd для перемещения между папками и ls для получения обзора элементов в каталоге.

Создание файлов и папок

В этом разделе вы узнаете, как создавать файлы и папки и управлять ими непосредственно из терминала с помощью некоторых новых команд. Кроме того, вы также продолжите узнавать информацию о содержимом каталога с помощью ls и перемещаться между папками с помощью cd.

Благодаря знаниям из этого раздела, вы сможете создавать и организовывать свои проекты в терминале.

Сначала убедитесь, что вашим текущим рабочим каталогом является Desktop. Затем используйте mkdir для создания новой папки с именем rp_terminal:

Windows

        PS> cd C:\Users\realpython\Desktop
PS> pwd
C:\Users\realpython\Desktop
PS> mkdir rp_terminal
    

Linux + macOS

        $ cd /Users/realpython/Desktop
$ pwd
/Users/realpython/Desktop
$ mkdir rp_terminal
    

Вы используете команду mkdir для создания нового каталога. Команда расшифровывается как make directory. Здесь вы создаете новый каталог rp_terminal.

Затем перейдите в rp_terminal/ и создайте новый файл с именем hello_terminal.py. Выберите свою операционную систему ниже и используйте соответствующую команду для конкретной платформы:

Windows

        PS> cd rp_terminal
PS> ni hello_terminal.py
    

Linux + macOS

        $ cd rp_terminal
$ touch hello_terminal.py
    

Когда вы запускаете команду touch, вы создаете пустой файл с заданным именем. В данном случае файл представляет собой скрипт Python с именем hello_terminal.py.

Если файл с указанным именем уже существует, то использование touch обновляет временную метку файла до текущей даты и времени, но не изменяет его содержимое. Команда touch также обновляет время доступа и модификации файла, даже если его содержимое остается неизменным.

Используйте ls, чтобы убедиться, что вы успешно создали файл:

        $ ls -l
total 0
-rw-r--r--@ 1 realpython  staff  0 Nov 27 12:09 hello_terminal.py
    

Между 0 и временной меткой написано, что hello_terminal.py в настоящее время пуст. Прежде чем вы начнете использовать команду echo для добавления содержания в hello_terminal.py, посмотрите, что происходит, когда вы вводите echo с некоторым текстом:

        $ echo 'print("Hello, terminal!")'
print("Hello, terminal!")
    

Как разработчик Python, вы знаете, что текст, который вы только что передали в echo, является вызовом функции print(). Точнее, команда echo отправляет строку в стандартный поток вывода (stdout).

Stdout – место назначения по умолчанию для данных, отправляемых программой командной строки. Данные отображаются на экране, но вы можете указать терминалу перенаправить stdout в файл:

        $ echo 'print("Hello, terminal!")' > hello_terminal.py
    

Опять же, вы используете echo для вывода заданной строки. Но на этот раз вы используете символ вставки > для отправки вывода в hello_terminal.py.

Примечание

Будьте осторожны при перенаправлении stdout на существующие файлы. Любое содержимое файла будет перезаписано без предупреждения.

Когда вы перенаправляете вывод команды echo в несуществующий файл, вы создаете файл на том же шаге.

Один из способов проверить, сработала ли команда, — снова просмотреть содержимое вашей папки:

        $ ls -l
total 8
-rw-r--r--@ 1 realpython  staff  26 Nov 27 12:12 hello_terminal.py
    

Отлично, сейчас размер hello_terminal.py 26 байт. Чтобы убедиться, что он содержит вызов функции print(), вы можете использовать команду cat:

        $ cat hello_terminal.py
print("Hello, terminal!")
    

К сожалению, команде cat не связана с кошками. Это сокращение от concatenate.

Когда вы используете cat с несколькими файлами в качестве аргументов, вы можете объединить их и отображать содержимое один за другим. Если вы используете cat только с одним файлом, то cat – это удобный способ отображения содержимого файла в терминале.

Теперь, когда вы знаете, что hello_terminal.py содержит допустимый код Python, вы можете запустить скрипт Python:

        $ python hello_terminal.py
Hello, terminal!

    

Когда вы используете команду python, терминал ищет исполняемый файл Python в вашем PATH.

Если вы запустите команду python без каких-либо аргументов, вы запустите интерактивный интерпретатор Python, также известный как REPL. Когда вы запускаете команду с файлом скрипта в качестве аргумента, Python запускает предоставленный скрипт.

В этом случае вы выполняете hello_terminal.py и видите результат своей функции print() непосредственно в терминале. Это работает, потому что print() использует stdout по умолчанию.

Примечание

Когда вы запускаете скрипт Python в терминале, он выводит все сообщения об ошибках в стандартный поток ошибок (stderr). Стандартный поток ошибок — это отдельный выходной канал, который используется специально для сообщений об ошибках, предупреждений и другой диагностической информации.

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

Благодаря знаниям, полученным в этом разделе, вы теперь можете создавать, редактировать и проверять файлы Python в терминале. Теперь вы хорошо подготовлены для перехода к работе с инструментом командной строки, который необходим на вашем пути в качестве разработчика Python. Он называется pip, и он позволяет вам добавлять внешние пакеты в ваши проекты Python.

Управление пакетами с помощью pip

Менеджер пакетов pip — важный инструмент для управления пакетами Python. Чтобы избежать установки пакетов непосредственно в вашу системную установку Python, вы можете использовать виртуальную среду.

Виртуальная среда предоставляет изолированный интерпретатор Python для вашего проекта. Любые пакеты, которые вы используете в этой среде, не зависят от вашего системного интерпретатора. Это означает, что вы можете хранить зависимости вашего проекта отдельно от других проектов и системы в целом.

Создайте виртуальную среду

Python имеет встроенный venv модуль для создания виртуальных сред. Этот модуль помогает создавать виртуальные среды с помощью изолированной установки Python. После того как вы активировали виртуальную среду, вы можете устанавливать в нее пакеты. Пакеты, которые вы устанавливаете в одну виртуальную среду, изолированы от всех других сред в вашей системе.

Вы можете выполнить следующие шаги, чтобы создать и активировать виртуальную среду с именем venv:

Windows

        PS> python -m venv venv
PS> venv\Scripts\activate
(venv) PS>
    

Linux + macOS

        Linux + macOS
    

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

Примечание

Когда вы закончите работу с этой виртуальной средой, вы можете деактивировать ее, выполнив команду deactivate.

Когда вы активируете виртуальную среду с помощью модуля Python venv, вы добавляете новую запись в PATH переменную среды. Новая запись указывает на расположение исполняемого файла Python виртуальной среды. Это гарант того, что когда вы запускаете команды или сценарии Python, они будут использовать этот конкретный исполняемый файл Python вместо любой другой версии Python, которая может быть установлена ​​в вашей системе.

Устанавливаем пакет

В этом разделе вы установите Rich library Уилла Макгугана, которая позволит вам создавать красочные текстовые приложения пользовательского интерфейса (TUI) для терминала.

Перед установкой rich проверьте, какие пакеты Python в настоящее время установлены в вашей виртуальной среде:

        (venv) $ python -m pip list
Package    Version
---------- -------
pip        22.3
setuptools 65.5.0
    

Выполнение команды python -m pip list выводит список всех пакетов, установленных в текущей среде. И pip, и setuptools – это пакеты по умолчанию, которые вы найдете при запуске новой виртуальной среды.

Для установки rich используйте следующую команду:

        (venv) $ python -m pip install rich
Collecting rich
  ...
Installing collected packages: commonmark, pygments, rich
Successfully installed commonmark-0.9.1 pygments-2.14.0 rich-13.0.1
    

Кроме rich, вы также установили некоторые другие зависимости, которые вам понадобятся, когда вы захотите их использовать с rich. Чтобы проверить все установленные на данный момент пакеты, вы можете запустить python -m pip list еще раз:

        (venv) $ python -m pip list
Package    Version
---------- -------
commonmark 0.9.1
pip        22.3
Pygments   2.14.0
rich       13.0.1
setuptools 65.5.0
    

Чтобы увидеть предлагаемые возможности rich, запустите rich без каких-либо аргументов:

        (venv) $ python -m rich
    

В зависимости от возможностей вашего терминала вы должны увидеть такие примеры:

⌨️ Терминал для начинающих: полезные команды для работы в командной строке Windows, Linux и MacOS

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

Теперь, когда ваш экран заполнен сверху вниз, вы можете снова очистить окно терминала. Для этого можно использовать clear команду:

        (venv) $ clear
    

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

В некоторых терминалах вы можете использовать Ctrl + L или Cmd + L в качестве сочетаний клавиш для очистки экрана.

В этом разделе вы узнали, как использовать pip непосредственно из терминала. Для любого Python-разработчика крайне важно знать, как использовать pip в терминале, поскольку это помогает эффективно управлять пакетами, используемых в проектах, и обновлять их.

Если вы хотите узнать больше о виртуальных средах и pip, вы можете ознакомиться с учебником Real Python по виртуальным средам Python и учебным пособием о том, как использовать Python pip для управления зависимостями ваших проектов. Оба являются важными инструментами, которые облегчат вашу жизнь как разработчика Python.

Еще один полезный инструмент для управления вашими проектами — Git. Читайте дальше, чтобы узнать, как улучшить свои навыки работы с терминалом и погрузиться в мир контроля версий с помощью Git.

Взаимодействие с Git

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

В этом разделе вы узнаете, как взаимодействовать с Git непосредственно из терминала. Вы будете инициализировать репозиторий Git, отслеживать файлы и создавать коммиты.

Для Git существует множество клиентов с графическим интерфейсом. Они могут быть удобны в использовании и помогут вам лучше понять логику Git.

Тем не менее, изучить основы взаимодействия с Git в терминале все же стоит. Изучение основных команд терминала Git поможет вам понять, как работает Git внутри.

Создание репозитория Git

Первым шагом в использовании Git является инициализация репозитория. Репозиторий — это контейнер, в котором хранятся все файлы вашего проекта, папки и метаданные.

Создайте новый репозиторий Git с помощью следующей команды:

        $ git init
Initialized empty Git repository in
⮑ /Users/realpython/Desktop/rp_terminal/.git/
    

Когда вы запускаете команду git init, Git создает пустой репозиторий в текущем рабочем каталоге. В свою очередь, это создает новый подкаталог с именем .git/, который содержит все необходимые файлы репозитория.

После инициализации репозитория вы можете проверить статус вашего репозитория:

        $ git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    hello_terminal.py
    venv/

nothing added to commit but untracked files present (use "git add" to track)
    

Команда git status показывает текущий статус вашего репозитория: на какой ветке вы находитесь и есть ли какие-либо коммиты.

Коммит Git — это моментальный снимок изменений, внесенных в файлы в репозитории Git. Когда вы вносите изменения в свои файлы и сохраняете их, вы можете сделать снимок этих изменений, создав фиксацию в ветке. Когда вы делаете новые коммиты, ветвь указывает на последние коммиты.

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

Кроме того, git status показывает, какие файлы Git не отслеживает. Вы можете игнорировать определенные файлы и папки, например, папку venv/, чтобы Git не отслеживал их.

Какие файлы игнорировать

Общее правило – игнорировать любые файлы, которые специфичны для вашей локальной среды разработки или файлы, которые генерируются вашим процессом сборки. Некоторые примеры файлов, которые обычно следует игнорировать, включают:

  • Файлы, содержащие конфиденциальную информацию, например, пароли или закрытые ключи.
  • Двоичные файлы, создаваемые процессом сборки, например, скомпилированные исполняемые файлы или файлы объектов.
  • Файлы, специфичные для вашей локальной среды разработки, такие как файлы виртуальной среды или файлы конфигурации редактора, специфичные для пользователя
  • Временные файлы или файлы, созданные вашей операционной системой, такие как .DS_Store в macOS или Thumbs.db в Windows
  • Логи или другие файлы, которые генерируются вашим приложением во время выполнения.

Просмотрите GitHub’s collection of .gitignore templates, чтобы получить представление о наиболее часто встречающихся файлах .gitignore. Там же вы найдете Python specific .gitignore example.

Вы можете игнорировать файлы в Git, создав файл .gitignore и указав в нем файлы и папки, которые вы хотите игнорировать:

        $ echo "venv" > .gitignore
    

Как вы узнали ранее, эта команда создает новый файл с именем .gitignore и записывает venv в него. Проверьте текущие элементы в вашем репозитории Git, используя другую команду, которую вы уже знаете:

        $ ls -a
.          .git          hello_terminal.py
..         .gitignore    venv
    

Теперь у вас есть .gitignore файл рядом с вашим hello_terminal.py файлом, вашей venv/папкой и .git/папкой. Чтобы проверить, игнорирует ли Git venv/папку, запустите git status еще раз:

        $ git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    .gitignore
    hello_terminal.py

nothing added to commit but untracked files present (use "git add" to track)
    

Отлично, Git теперь показывает только файлы .gitignore и hello_terminal.py как неотслеживаемые файлы. Git знает, что файлы есть, но вы еще не добавили их в репозиторий.

Отслеживание файлов с помощью Git

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

Вы используете git add команду, чтобы сообщить Git, какие файлы вы хотите отслеживать:

        $ git add .
    

Помните точку . в списке каталогов раньше? Точка указывает на текущий каталог. Использование . в конце команды git add указывает Git отслеживать все файлы в текущем каталоге. После того, как вы добавили файлы в репозиторий, вы можете проверить статус ваших файлов с помощью git status команды:

        $ git status
On branch main

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
    new file:   .gitignore
    new file:   hello_terminal.py
    

В выводе видно, что файлы hello_terminal.py и .gitignore добавлены и готовы к фиксации:

        $ git commit -m "Initiate git repository"
[main (root-commit) 7b20833] Initiate git repository
 2 files changed, 2 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 hello_terminal.py
    

С помощью команды git commit вы делаете снимок текущего состояния ваших файлов и сохраняете его в истории репозитория. Флаг -m добавляет сообщение с описанием ваших изменений. Вывод показывает ветку, в которой вы находитесь, и количество измененных файлов.

После того, как вы зафиксируете какие-либо изменения, рекомендуется снова проверить состояние вашего репозитория Git:

        $ git status
On branch main
nothing to commit, working tree clean
    

Видно, что коммитить нечего, а это означает, что все изменения были успешно зафиксированы.

Рабочий процесс, который вы использовали в этом разделе, является типичным при использовании Git в терминале. Вы используете команду git add, чтобы сообщить Git, какие файлы отслеживать. Затем вы используете git commit для создания снимка текущего состояния ваших файлов и сохраняете его в истории репозитория.

Кроме того, рекомендуется часто использовать git status для проверки текущего состояния вашего репозитория.

Хотя вы получили некое представление об использовании Git в терминале, Git может предложить вам как разработчику Python гораздо больше. Если вы хотите узнать больше о Git, вы можете ознакомиться с введением в Git и GitHub для разработчиков Python и изучить дополнительные советы по работе с Git для разработчиков Python.

Следующие шаги

Чем больше вы пользуетесь терминалом, тем привычнее вам будет. Интересный способ внедрить терминал в свои рабочие процессы в качестве разработчика Python — создать скрипты Python с интерфейсами командной строки. Например, вы можете создать:

  • Приложение-викторина с Python
  • Средство проверки подключения к сайту в Python
  • Приложение To-Do из командной строки с Python и Typer
  • Генератор дерева каталогов Python для командной строки
  • Приложение Weather CLI с Python
  • Wordle Clone с Python и Rich

Помимо использования pip и Git для управления вашими проектами Python, есть еще больше примеров с использованием терминала:

  • Интерфейсы командной строки. Многие популярные библиотеки и фреймворки Python, такие как Django , Flask и Poetry, включают в себя интерфейсы командной строки, которые позволяют выполнять такие задачи, как создание новых проектов, запуск серверов разработки и управление базами данных.
  • Автоматизация и сценарии. Терминал позволяет автоматизировать повторяющиеся задачи и создавать сценарии для управления рабочим процессом разработки, например, для запуска тестов или развертывания приложения.
  • Отладка. Терминал может быть полезен для отладки вашего кода. Например, вы можете использовать print()или logging in Python, чтобы вывести что-либо в терминале и понять, что происходит в вашем коде. Вы также можете использовать pdb для отладки кода Python.
  • Производительность. Многие инструменты командной строки работают быстрее, чем их аналоги с графическим интерфейсом, и идеально подходят для работы с большими наборами данных или выполнения сложных задач, таких как обработка и анализ данных.

В целом, терминал — это мощный инструмент, который может помочь вам оптимизировать рабочий процесс разработки, автоматизировать задачи, отлаживать код и получать доступ к расширенным функциям библиотек и фреймворков. С практикой вы обнаружите, что терминал — бесценный инструмент для вашего пути в качестве разработчика Python.

Заключение

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

В этом уроке вы узнали, как:

  • Найти терминал в операционной системе
  • Открыть терминал
  • Осуществить навигацию по файловой системе с помощью основных команд
  • Создать файлы и папки с помощью терминала
  • Управлять пакетами с помощью pip команд
  • Отслеживать файлы с помощью Git в терминале

Вы улучшили свои навыки программирования, научившись выполнять три действительно важные задачи в терминале: перемещаться по файловой системе, управлять пакетами Python с помощью pip и делать коммиты в Git. Изучение команд терминала — отличная инвестиция для вас как для Python-разработчика. Просто не торопитесь и постепенно знакомьтесь с этим мощным инструментом. Достаточно скоро он станет важным инструментом, без которого вы не сможете жить.

***

***

Материалы по теме

  • 🐧 Терминал для тестировщика: консольные команды Unix/Linux, которые нужно знать наизусть
  • Терминал Linux: видеокурс по работе на примере Ubuntu
  • 6 команд терминала и пара комбинаций, полезных для начинающих разработчиков

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сделать так чтобы windows 10 не требовал пароль при входе
  • Система управления базами данных windows
  • Как посмотреть маршрутизацию в сети windows
  • Сборка windows 2003 server
  • Windows remote desktop ipad