Command-Line Interface PDF
Document Details
Uploaded by SeasonedJoy1900
Kennesaw State University
Tags
Summary
This document outlines accessing command-line interfaces in various operating systems, particularly focusing on command prompts in Windows, terminals in macOS and Linux, and introduces basic command-line concepts and usage.
Full Transcript
Command-Line Interface15 NOTE If you're using a Windows system, this is a great opportunity to jump ahead to Chapter 22 and try some virtualization. Consider loading up a virtual machine and installing Linux so you can practice the Linux command line. Check out and install my favorite virtualizati...
Command-Line Interface15 NOTE If you're using a Windows system, this is a great opportunity to jump ahead to Chapter 22 and try some virtualization. Consider loading up a virtual machine and installing Linux so you can practice the Linux command line. Check out and install my favorite virtualization tool, Oracle VirtualBox at https://www.virtualbox.org, and then download an ISO file from. How to access the **Command-Line Interface (CLI)** in Windows, specifically focusing on the Command Prompt. **Accessing Command Prompt:** 1. **Using the Start Menu:** - **Open** the **Start menu** or use the **Search bar.** - **Type cmd** to find Command Prompt. - **Press Enter** to open it. **Windows 11 Specifics:** - In Windows 11, Command Prompt opens within the new Windows Terminal. - The interface may look slightly different from Windows 10. **Closing Command Prompt:** - **Click** the **Close button** in the upper-right corner. - Alternatively, type exit and press Enter to close it. **Running Commands with Elevated Privileges:** - Some commands need administrative privileges. - If required, a UAC (User Account Control) dialog will appear, asking for permission. - **To run Command Prompt as an administrator:** - **Right-click** the **Command Prompt shortcut**. - **Select Run as administrator**. - Enter the administrator password or credentials if prompted. **Accessing the Command-Line Interface in macOS and Linux** The passage provides instructions on how to access the **Command-Line Interface (CLI)** on macOS and Linux systems. **Accessing the Terminal in macOS:** 1. Using **Finder: Navigate to Applications \> Utilities \> Terminal.** 2. Using **Spotlight**: **Press Command-Spacebar, type \"terminal,\"** and **press Enter**. **Accessing the Terminal in Linux:** - Terminal emulator names vary by distribution (e.g., Konsole Terminal, GNOME Terminal). - On Ubuntu Linux, it\'s called Terminal. - Use the desktop\'s search function, type \"terminal,\" and press Enter. **Running Commands with Advanced Privileges:** - Use **sudo** **or su** for superuser (root) privileges. - **Using sudo:** - Type sudo before a command. - Enter your password when prompted. - **Using su:** - **Type su** and **press Enter.** - Enter the root password. - This starts a new shell session as root (prompt changes from \$ to \#). - Type exit to return to your normal shell session. **\ The Prompt** Regardless of what shell you use, the command line always focuses on a specific folder, the working directory, usually indicated by the prompt. If any commands use a relative file path, it will be relative to the current working directory. Here's an example: in Windows, if you see a prompt that looks like the following line, you know that the focus is on the root directory of the C: drive: C:\\\> In a UNIX-like OS the prompt is subtly different, but functionally the same. First, these systems don't use the Windows drive lettering concept: all forms of storage are simply mounted as folders. Second, prompts on these systems usually show the logged-on user and system as well as the current directory. Third, paths on these systems use a forward slash (/) instead of a backslash (\\). This prompt shows user mike is on the "server" system and is in the home directory: mike\@server:/home\$ If you're working with files from the command line, it's important to focus the prompt on the drive and folder where you want to work. **Closing the Terminal** Closing a command prompt is easy and is done the same way in Windows, macOS, and Linux. From the CLI you want to close, just type **exit** and press enter. This technically just exits the shell itself, but many terminal emulators will automatically close the window or tab when the shell terminates. If yours doesn't, manually close the tab or window as well. 1\. **Drive Letter Assignment in Windows:** - Windows assigns letters to drives, with C: typically representing the primary hard drive. Additional drives (e.g., external USBs, optical drives) receive subsequent letters. 2**. UNIX-like Systems:** - These systems do not use drive letters. The root drive is represented by a single slash (/). Additional storage devices are accessed via a mounting process, often found under directories like /mount or /media in Linux, and /Volumes in macOS. **3. File and Folder Hierarchy:** - The root directory is the top level in the file system tree. Subfolders can exist within folders, and multiple subfolders can be created under any folder. - Files can have the same name in different folders, but not within the same directory. **4. File Path Definitions:** - A file path defines its location: - Absolute Path: Provides the full route from the root. - Relative Path: Offers directions based on the current directory. **5. Case** **Sensitivity:** - UNIX-like systems differentiate between uppercase and lowercase in folder names, allowing for names like \"Mike\" and \"mike\" in the same directory. In contrast, Windows and macOS treat names as equivalent, so such differentiation is not possible. **Mastering Fundamental Commands** All commands in every command-line interface use a similar structure and you run them the same way. You type the name of the command, followed by the target of that command and any modifications of that command that you want to apply, and then press enter to execute the command. You specify a modification with its switch or option (often a special character such as / or - followed by one or more letters, numbers, or words), which usually follows either the command or the target, depending on the command. The proper way to write a command is called its syntax. \\ when the syntax calls for a /. Since the CLI doesn't have an easy-to-discover button or menu for every command, you have to learn the correct syntax for each. (There's no shame in looking it up each time---there are plenty of commands I can't keep straight--- but it will slow you down.) Consider these two common forms (the brackets are just placeholders---you wouldn't type them): \[command\] \[target (if any)\] \[switches\] or \[command\] \[switches\] \[target (if any)\] How do you know what switches are allowed? How do you know whether the switches come before or after the target? Don't just guess, look it up! 1**. Windows Command Prompt:** - Use the \`/?" switch with a command to display help documentation, including syntax, available switches, and their functions. - **Example:** \[command name\] /? **2. PowerShell:** - Execute the Get-Help cmdlet followed by the command name for detailed information about the command, including syntax and options. - Example: Get-Help \[command name\] **3. UNIX-like Systems:** - Use the man command followed by the command name to open its manual page, which provides comprehensive details on usage and switches. - **Example:** man \[command name\] **Command Types** 1. Built-in Commands: - **Definition:** Built-in commands are integrated directly into the shell itself. They do not require spawning a separate process, making them quicker for simple operations. They allow immediate shell interaction and are essential for navigation and environment control. - **Examples in Linux/Unix:** - **cd:** Changes the current directory. - **echo:** Outputs input text or variables to the terminal. - **pwd:** Prints the current working directory. - **exit:** Closes the current shell session. - Significance: Built-ins are crucial for manipulating the shell environment, including directory navigation, variable management, and shell control functions. 2. **External Commands:** - Definition: These are standalone executable files typically located in system directories such as **/bin, /usr/bin, and /usr/local/bin**. When invoked, the shell locates these files and runs them as separate processes. - **Examples in Linux/Unix:** - **ls:** Lists directory contents. - **grep:** Searches input text using patterns. - **tar**: Archives files. - **curl:** Fetches data from or to a server, using standard protocols. - **Significance:** External commands extend the shell\'s capabilities with a wide range of functionalities, from file manipulation and text processing to networking and system management. 3. **Shell Scripts:** - **Definition:** Shell scripts are files containing a sequence of commands that are executed by the shell interpreter. They are used to automate tasks and can incorporate logic, loops, and variables. - **Characteristics:** - Typically end with a .sh extension. - Allow procedural programming within the command-line interface. - Can be executed by specifying the interpreter (e.g., bash script.sh) or directly if they are executable and have a shebang (\#!/bin/bash). - **Significance:** Shell scripts streamline repetitive tasks, perform batch processing, automate system administration tasks, and serve as deployment scripts. 4. **Pipelines:** - **Definition:** A pipeline chains commands together by using the output of one command as the input for another, facilitated by the pipe symbol (\|). - **Examples:** - **ls -l \| grep \"txt\":** Lists files and filters those containing \"txt\". - **ps aux \| grep python:** Displays processes filtered to show those containing \"python\". - **Significance:** Pipelines enhance command functionality by allowing complex data processing and transformation using simple command sequences, enabling powerful UNIX idioms for tasks. 5. **Redirects:** - **Definition:** Redirection alters the standard input/output of commands using operators like \>, \\>, and 2\>. - **Examples:** - **command \> file.txt:** Directs output to file.txt, overwriting existing content. - **command \>\> file.txt:** Appends output to file.txt. - **command \< input.txt:** Reads input from input.txt. - **command 2\> error.log:** Redirects error messages to error.log. - **Significance:** Redirection is fundamental for efficient data handling, enabling users to capture command outputs, handle errors, and utilize files as input/output sources. 6. **Arguments and Options:** - **Definition:** Commands can accept arguments, which are the specific data elements needed for execution, and options (or flags), which modify command behavior, typically prefixed by a dash (-) or double dash (\--). - **Examples:** - **ls -l /home/user:** Lists files with detailed information under /home/user. - **grep -i \"pattern\" file.txt:** Searches for \"pattern\" case-insensitively. - **Significance:** Arguments and options increase command flexibility and specificity, enabling granular control over command execution. 7. **Environment Commands:** - **Definition:** These manipulate or display environment variables, which are dynamic values affecting process behavior and shell sessions. - **Examples in Linux/Unix:** - **export VAR=value:** Sets an environment variable for child processes. - **printenv:** Displays all environment variables and their values. - **env:** Runs commands with a modified environment. - **Significance:** Environment variables control a wide range of system and application settings, such as paths, user settings, and locale configurations, making environment commands crucial for system configuration. **Changing Directory Focus: The cd Command** The cd command is essential for navigating the file system in Windows, Linux, and Unix systems. Here\'s an overview of how it works across these platforms: Basic Usage **Change Directory:** The primary function of cd is to change the current directory to another directory. **Example:** **To change to a directory called \"Documents\":** **cd Documents** - Absolute Path: You can specify an absolute path to navigate directly to a directory regardless of your current location. **Example:** To change to \"C:\\Program Files\" (Windows) or \"/usr/local/bin\" (Linux/Unix): cd C:\\Program Files cd /usr/local/bin **Relative Paths** - You can also use relative paths based on your current directory. **Example:** If you are in \"C:\\Users\" (Windows) or \"/home\" (Linux/Unix) and want to go to \"C:\\Users\\YourUsername\\Documents\" or \"/home/YourUsername/Documents\": cd YourUsername\\Documents cd YourUsername/Documents **Special Directory References** - Parent Directory: Use .. to move up one level in the directory structure. **Example:** cd.. **Home Directory:** In Linux and Unix, \~ can be used to quickly navigate to the home directory. **Example:** cd \~ **Viewing Current Directory** To view the current directory you are in, you can use: - Windows: cd or echo %cd% - Linux/Unix: pwd (print working directory) **Use Cases** - The cd command is commonly used in scripts or command line operations to navigate the file system effectively, making it easier to access files and run programs located in different directories. **Unix-specific features** - In Unix-like systems (including Linux), cd has some additional features: - Previous Directory: Use cd - to switch to the previous working directory. - CDPATH: This environment variable can be set to define a search path for the cd command, similar to PATH for executables. - Subdirectory Stack: Unix shells often provide commands like pushd and popd to maintain a stack of directories, allowing for more complex navigation patterns. **Errors Are Good!** Error messages, whether from the command prompt or graphical interfaces, are beneficial. They indicate what went wrong, enabling users to correct mistakes. There\'s no harm in typing a command like \`dir\` or \`cd\` incorrectly, so you can freely experiment and learn from errors. **Key Points on Error Messages:** \- They are crucial for understanding and fixing mistakes. \- Experimenting with commands allows you to learn in a safe environment. **UNIX System Note:** \- On UNIX systems, it\'s considered poor practice to create files and folders in the root directory (/). Root permissions are required due to Linux\'s multiuser history, which helps protect the system from user actions that might disrupt the OS. Embrace error messages and leverage them as valuable learning tools while respecting system conventions to prevent issues. **Moving Between Drives in Windows** Moving between drives in Windows is a straightforward process, whether you\'re using File Explorer, the Command Prompt, or PowerShell. **1. Using File Explorer:** - **Open File Explorer:** You can do this by **clicking the folder icon** in **your taskbar** or pressing **Windows + E.** - **Select Drive:** In the left sidebar, you'll see a list of drives (like C:, D:, E:, etc.). Simply click on the drive you want to access, and it will display the contents of that drive. 2\. **Using the Command Prompt:** - **Open Command Prompt:** **Press Windows + R, type cmd, and hit Enter.** - **Change Drive:** To switch to another drive, simply type the drive letter followed by a colon (e.g., D:) and press Enter. This will change the prompt to reflect the new drive. - **Navigate Directories:** You can use cd followed by the folder name to move into folders on that drive (e.g., cd FolderName). 3\. **Using PowerShell:** - **Open PowerShell:** **Press Windows + X** and **select Windows PowerShell**. - **Change Drive:** Similar to **Command Prompt**, type the drive letter followed by a colon (e.g., D:) and **press Enter.** - **Navigate:** Use Set-Location (or the alias cd) to change directories within the selected drive. 4\. **Keyboard Shortcuts:** - In **File Explorer**, you can quickly switch between drives using the address bar. **Click** on the **dropdown arrow**, and you'll see a list of your drives. - Use **Alt + Left Arrow** and **Alt + Right** Arrow to navigate back and forth between previously accessed folders. **Additional Tips:** - **Creating Shortcuts:** You can create shortcuts to frequently used folders on different drives by right-clicking on the folder, selecting \"Create shortcut,\" and placing them on your desktop or quick access bar in File Explorer. - **File Transfer:** To move files between drives, you can drag and drop them between folders in File Explorer or use copy and paste commands in either the GUI or command line. **Moving Between Drives in macOS and Linux** Moving between drives in macOS is simple and can be done through Finder, the Terminal, or the desktop. 1\. **Using Finder:** - **Open Finder**: **Click on** the **Finder icon** in the **Dock** (the smiley face). - **Access Drives:** In the **Finder sidebar**, look under the \"**Locations\" section**. Here, you'll see all connected drives, including external drives and network shares. - Select Drive: Click **on** the drive you want to access to view its contents. You can also click on \"**All My Files**\" to browse files across drives. - **Navigate Folders**: Once in a drive, you can **double-click on folders** to navigate deeper or use the back and forward buttons in the **Finder toolbar.** 2\. **Using the Desktop:** - **Show Drives on Desktop**: Make sure your drives are set to show on the desktop. Go to **Finder \> Preferences \> General**, and **check \"External disks**\" and \"**CDs, DVDs**, and **iPods.\"** - **Access from Desktop:** You can simply **double-click on** the drive icons on your desktop to open them. 3\. **Using Terminal:** - **Open Terminal**: You can find it in **Applications \> Utilities \> Terminal** or by searching using **Spotlight (Command + Space and type \"Terminal\").** - **List Drives**: Use the **ls /Volumes command** to see all mounted drives. - **Change Drive:** To navigate to a drive, **type cd /Volumes/YourDriveName** and **press Enter**. **Replace \"YourDriveName**\" with the name of the drive you want to access. - **Navigate Directories**: You can use other commands like ls to list files and cd to change into directories. 4\. **Keyboard Shortcuts:** - **Switching Between Drives in Finder:** Use **Command + Shift + N** to create a new Finder window and navigate to different drives more easily. - **Quickly Open Drives: Press Command + Option + D** to hide or show the Dock, giving you quick access to your Finder windows. **Additional Tips:** - **Creating Aliases:** You can create aliases (similar to shortcuts) for frequently accessed folders or drives. **Right-click on** a folder or drive, **select \"Make Alias**,\" and drag it to your desktop or where you\'d like easy access. - **Copying/Moving Files:** You can drag and drop files between drives in **Finde**r, or use **Command + C to copy and Command + V to paste.** Navigating between drives in Linux can be accomplished using several methods, depending on whether you prefer a graphical user interface (GUI) or the command line. **1. Using a Graphical User Interface (GUI):** Most Linux distributions come with a file manager (like Nautilus in GNOME or Dolphin in KDE) that allows you to easily access and manage files on different drives. - **Open File Manager: **Locate your file manager in the applications menu or on your desktop. - **Access Drives: **In the file manager, you\'ll typically see mounted drives listed in the sidebar under \"**Devices**\" or \"**Location**s.\" Click on the drive you want to access. - **Browse Files: **Double-click on folders to navigate through the contents of the selected drive. 2\. **Using the Terminal:** For users who prefer the command-line interface, navigating between drives can be done efficiently using commands. - **Open Terminal: **You can find it in the applications menu, or **press Ctrl + Alt + T** in many distributions. - **List Mounted Drives: **Use the **lsblk** command to list all block devices (drives) attached to your system. **lsblk** - **Change Directories:** To switch to a specific drive, use the cd command followed by the mount point of the drive (usually located in /mnt or /media). **cd /media/YourUsername/DriveName** Replace YourUsername with your actual username and DriveName with the name of the drive you want to access. - Command to List Files: After changing to the desired drive, you can list files with: **ls** 3\. **Mounting Drives:** If your drive isn't mounted, you will need to mount it first. Here's how to do that: - Identify the Drive: Use the lsblk command to find the identifier **(e.g., /dev/sdb1**) of the unmounted drive. - Create a Mount Point (if necessary): Determine where you want to mount the drive. **sudo mkdir /mnt/mydrive** - **Mount the Drive:** sudo mount /dev/sdb1 /mnt/mydrive Replace /dev/sdb1 with your drive\'s identifier and /mnt/mydrive with your desired mount point. 4\. **File Transfer:** - Copying Files: To copy files between drives, use the cp command. **cp /path/to/source/file /path/to/destinationforce:** Forces a refresh of all Group Policy settings. This applies both user and computer policies, regardless of whether they have changed. **gpupdate /force** - **/logoff:** Indicates that a logoff is required to apply some policy changes (like user-related settings). It can prompt the user to log off after the update. **gpupdate /logoff** - /boot: Indicates that a reboot is required for some policy changes (like certain security settings). It can prompt the user to reboot after the update. **gpupdate /boot** - /target:{computer \| user}: Specifies whether to update settings for the computer or the current user. **gpupdate /target:computer** **How to Use gpupdate:** 1. **Open Command Prompt:** - **Press Windows + R, type cmd, and hit Enter.** You can also search for \"Command Prompt\" in the Start menu. 2. **Run the Command:** - Type gpupdate, possibly with one of the options mentioned above, and press Enter. 3. **Review the Output:** - After running the command, you will see a message indicating whether the update was successful, and if any logoff or reboot is required. **gpresult** The **gpresult** command is a useful tool in Windows that provides detailed information about Group Policy settings applied to a user or computer. It helps administrators troubleshoot and verify that the correct Group Policies are being applied and identify any configuration problems. **Basic Usage** To use **gpresult,** open the Command Prompt with administrative privileges: **cmd:** **gpresult \[options\]** **Common Options and Usage Scenarios** **View Summary for the Current User:** **Cmd:** **gpresult /r** This command displays a summary of Group Policy settings for the currently logged-in user and the computer. It shows the policies that have been applied, their sources, and the last time they were applied. **View Summary for a Specific User:** **Cmd:** **gpresult /r /user username** Replace \`username\` with the actual username to view Group Policy information for that user. **View Detailed Information:** **Cmd:** **gpresult /v** This command provides verbose output, showing detailed information including policies applied, their settings, and any WMI filters used. **Generate a Report in HTML Format:** **cmd** **gpresult /h outputfile.html** Replace \`outputfile.html\` with the desired file path to generate an HTML report. This report can be opened in any web browser for easier viewing and analysis. **Run for a Remote Computer:** **Cmd:** **gpresult /s remotecomputername** Replace \`remotecomputername\` with the name of the remote computer to query its Group Policy results. **Target Specific User on a Remote System:** **cmd:** **gpresult /s remotecomputername /user username /v** This command will give verbose policy information for a specified user on a specified remote computer. **Key Details from gpresult:** **Applied Group Policies**: Lists both computer-level and user-level policies that are currently applied. **Group Policy Objects (GPOs):** Displays which GPOs are applied and in what order, along with their status (enabled, disabled, etc.). **Security Group Memberships:** Shows the security groups that the user belongs to, which can affect policy application. **Effective Policies:** Indicates which settings are enforced due to GPOs, specifying conflicting or overridden settings through security filtering or precedence. **Usage Considerations** **Administrative Privileges**: Running **gpresult** to retrieve complete and accurate results may require administrative privileges, especially when accessing system-wide (as opposed to user-specific) settings or querying remote systems. **Troubleshooting:** Use **gpresult** to verify policy application issues, such as when certain GPO settings do not seem to apply as intended. **HTML Reports:** Generating HTML reports is particularly useful for documentation or sharing detailed policy information with team members or management. **sfc** **The System File Checker (SFC)** is a utility in Microsoft Windows that allows users to scan for and restore corruptions in Windows system files. It\'s a useful tool for troubleshooting problems related to file integrity within the Windows operating system. Here are some key points about the System File Checker: 1\. **Purpose:** The main purpose of the SFC is to scan the integrity of all protected system files and replace any that are corrupted, modified, or missing with the correct version. 2\. **Command Usage**: You can run the System File Checker tool via the Command Prompt. To do this, open Command Prompt with administrative privileges and run the command: **sfc /scannow** This command will perform a complete scan of the system files and attempt to repair any issues it finds. 3\. **Common Scenarios:** It\'s often used when there are errors related to Windows functionalities, or if Windows is not behaving as expected. It can resolve issues like applications not starting properly or unexpected system errors. 4\. **Running Offline:** SFC can also be used to repair system files when the operating system is offline or if you cannot boot into Windows normally. You can do this by booting from a Windows installation media and accessing the Command Prompt from the recovery options. 5\. **Limitations:** While SFC can fix many issues related to system file corruption, it may not be able to repair all problems, especially if there are deep-seated issues with the operating system or if the corruption is extensive. 6\. **DISM:** If SFC is unable to fix a problem or if additional issues are present, it can be useful to run the Deployment Imaging Service and Management Tool (DISM) as an additional step. The relevant DISM command is: **DISM /Online /Cleanup-Image /RestoreHealth** This command can check for component store corruption, repair it using Windows Update, and prepare files for the System File Checker. **shutdown** The \`shutdown\` command in Windows is used to shut down, restart, or log off a computer. It can be quite useful for managing systems remotely or for scripting automated shutdown procedures. Here\'s how to use the \`shutdown\` command: **Basic Usage** The basic syntax of the \`shutdown\` command is: **shutdown \[options\]** Common Options and Examples \- **Shut Down the Computer:** **shutdown /s** This command will initiate a shutdown of the computer. \- **Restart the Computer:** **shutdown /r** This command will restart the computer. \- **Log Off the Current User:** **shutdown /l** This command logs off the current user. \- **Specify Time Delay:** **shutdown /s /t 60** This command schedules a shutdown in 60 seconds. You can adjust the number of seconds as needed. \- **Abort a Scheduled Shutdown:** **shutdown /a** This command will abort any shutdown that is in progress during the grace period. \- **Display a Shutdown Message:** **shutdown /s /c \"System will shut down for maintenance.\"** The \`/c\` option adds a comment that will be displayed to users about the reason for the shutdown (limited to 512 characters). **- Force Running Applications to Close:** **shutdown /s /f** The \`/f\` option forces running applications to close without warning users. \- **Shutdown and Prepare for a Fast Startup** (available in Windows 8 and later): shutdown /hybrid This command performs a shutdown that prepares for fast startup. \- **Hibernate the Computer:** shutdown /h This command puts the computer into hibernate mode. **Remote Shutdown** If you need to shut down a remote computer: **- Shut Down a Remote Computer:** **shutdown /s /m \\\\RemoteComputerName** \- **Additional Options:** \- You can combine \`/m\` with other options to force or schedule a shutdown on a remote machine. **Important Considerations** \- **Administrative Privileges**: Executing the \`shutdown\` command, especially with options that affect other users or remote systems, usually requires administrative privileges. \- **Network Configuration**: For remote shutdowns, ensure that the network settings and permissions allow for remote management and that firewall rules permit such actions. \- **Use with Caution**: The \`shutdown\` command can disrupt current operations on your system or target systems. Be mindful of active users or unsaved work. **Keyboard Shortcuts** The \`dir\` command is a command-line utility used to list the contents of directories in Windows operating systems. It\'s similar to the \`ls\` command in Unix/Linux-based systems. Here is how the \`dir\` command works and some of its options: **Basic Usage** 1\. **Open Command Prompt**: To use the \`dir\` command, you first need to open Command Prompt. You can do this by typing \`cmd\` in the Windows search bar and pressing Enter. 2\. **Basic Command:** Simply type \`dir\` and press Enter to display a list of files and subdirectories in the current directory. **Syntax** **dir \[\:\]\[\\]\[\\] \[/A\[\[:\]attributes\]\] \[/B\] \[/C\] \[/D\] \[/L\] \[/N\] \[/O\[\[:\]sortorder\]\] \[/P\] \[/Q\] \[/R\] \[/S\] \[/T\[\[:\]timefield\]\] \[/W\] \[/X\] \[/4\]** **Common Options** **/A**: Displays files with specified attributes. **/B**: Uses bare format (no heading information or summary). **/D**: Shows contents sorted by column. **/L:** Uses lowercase. **/N:** Displays a long list format where filenames are on the far right. **/O:** Sorts the output according to sort order. You can use **N** for name, **E** for extension, **D** for date, etc. **/P:** Pauses after each screen of information. **/Q:** Displays file ownership information. **/S:** Lists every occurrence of the specified file name within the specified directory and all subdirectories. **/T:** Controls which time field is displayed or used for sorting. Available options are \`C\` for Creation, \`A\` for Last Access, and \`W\` for Last Written. **/W:** Displays the listing in wide format. **/X:** Displays short names generated for non-8dot3 file names. **/4:** Displays the year with four digits. **Example Usage** - **Basic Directory Listing:** \`dir\` - **List all files with details, sorted by name**: \`dir /O:N\` - **List contents of a specific path: \`dir** C:\\Users\\YourName\\Documents\` - **List with a pause per page: \`dir** /P\` **Assorted macOS and Linux Commands** **See Running Processes: top and ps** The (veryold**) ps command** provides detailed and customizable information about the processes running on your system at the moment you run the command. The top command is an interactive, continuously updating monitor of what's running---and by default it focuses on resource-hungry processes. Generally, use top to monitor or investigate system performance, and use ps to look for specific processes. **top** When you just run top by itself, you get the default settings: the screen divided with the top portion showing system and resource information and the lower portion showing running processes. Once you start top, you use your keyboard to control it. Different versions of top have different options, so the first thing to try is to press ? for information about all of the interactive options. You can press q to close this help view, and press q from the main resource view to close top entirely. The ps command is so old that it has two totally different types of switch sets! If you just run ps by itself, it won't list much. We would have to get very deep in the weeds to understand exactly why---so instead we'll run one of the most common examples of ps: **ps aux**. The "aux" bit here is actually three separate switches (using the older legacy switch set): a = processes for all users, u = show process owner, and x = process not attached to a terminal. mike\@server:\~\$ ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.2 33968 4416 ? Ss 11:08 0:00 /sbin/init Note that ps aux usually writes out a ton of lines. I'm going to cut most of them out for space, but before we look at any more, let's discuss what these columns actually mean: USER: Who is running this process PID: The process ID number assigned to the process %CPU: What percentage of CPU power this process is using %MEM: What percentage of memory this process is using VSZ: Total paged memory in kilobytes RSS: Total physical memory in kilobytes TTY: The terminal that is taking the process's output STAT: S = waiting, R = running, l = multithreaded, + = foreground process START: When the process was started TIME: Length of time process has been running COMMAND: Name of the executable that created this process Now for a few more lines of output: root 2188 0.0 0.0 0 0 ? S 11:08 0:04 \[kworker/0:2\] mike 2218 0.0 1.5 574732 30908 ? Sl 11:08 0:03 gnome-terminal mike 2225 0.0 0.0 14828 1916 ? S 11:09 0:00 gnome-pty-helpe mike 2226 0.0 0.2 26820 5244 pts/10 Ss 11:09 0:00 bash mike 2267 0.0 1.0 571544 20856 ? Sl 11:09 0:00 update-notifier root 2570 0.0 0.0 0 0 ? S 14:19 0:00 \[kworker/u2:1\] root 2577 0.0 0.0 0 0 ? S 14:29 0:00 \[kworker/u2:0\] root 2578 0.0 0.0 0 0 ? S 14:34 0:00 \[kworker/u2:2\] mike 2579 0.0 0.1 22648 2568 pts/10 R+ 14:34 0:00 ps aux mike\@server:\~\$ A big problem with ps aux is the enormous output I mentioned. There are a number of ways to make dealing with this output easier (including different commands), but the most common is to pipe its output into a pager (like less, or more) for reading, or pipe it into a filter such as grep, which we'll discuss next. **grep** The grep command is a filter: it enables you to search through text files or command output to find specific information and filter out the rest. For example, finding a specific process is easy if you combine grep with the ps command. Let's say LibreOffice froze while opening a document and I need to kill it. I have no idea what the PID is, but I can use grep with ps to find it. I know the command uses the word "libre," so I type mike\@server:\~\$ ps aux \| grep libre mike 2524 0.0 0.2 145804 5652 ? Sl 14:12 0:00 /usr/lib/ libreoffice/program/oosplash \--writer mike 2543 0.0 5.5 1140216 114080 ? Sl 14:12 0:01 /usr/lib/ libreoffice/program/soffice.bin \--writer \--splash-pipe=5 So I see there are two processes from LibreOffice: 2524 and 2543. Cool! The grep command can find any string of text and show you the line it was in. This is only a light overview of one of the most powerful tools in UNIX. If you need to look in anything to find a string of text, grep is a good place to start. **find** Another big workhorse on UNIX is the find command, which can plow through all of the files and folders in a directory (and all of its subdirectories) and output a list containing only the ones that match some criteria of your choosing. When I say criteria, the following are some good examples: Its file is bigger than, smaller than, or exactly some size. It was created or modified before, on, or after some date (or some number of seconds/minutes/hours/days ago). It has (or doesn't have) certain permissions. Its name does (or doesn't) match a pattern. If you just run **find** all by itself, find will plow through all of the files in your current working directory without using any criteria at all---it'll list all of them! Give it a try (though it will output a lot if you are in a big directory). If that doesn't output much, run **find /etc/** to get the same effect on a specific directory. This isn't very useful on its own, so let's try out some criteria. Imagine you are asked to collect and archive all PDF documents in any user's home directory on a Linux laptop, wipe the device, and reinstall the OS. One of the find command's many options is perfect for this job: the -iname option adds a case-insensitive name criteria that can use a wildcard pattern. Here's how this search looks on my system (though I'm just including a few matches): mike\@server:\~\$ find /home/ -iname \"\*.pdf\" /home/mike/Downloads/CompTIA A+ 220-1101 Exam Objectives (4.0).pdf /home/mike/Downloads/CompTIA A+ 220-1102 Exam Objectives (4.0).pdf /home/mike/research/the-UNIX-command-language-(1976).pdf /home/mike/Downloads/receipts/United Airlines - Flight Check In.pdf... This searches each user's home directory within the /home/ directory, and prints out every file that ends with the.pdf extension (regardless of case---including.PDF,.Pdf, and so on). Fair warning: if you don't have permission to read all of the user directories on your system, find will emit a permission error for each one it can't search. **apt-get/APT** For Linux distros in the Debian family tree (like Ubuntu and Mint), we use APT, the advanced packaging tool. The apt-get command enables you to manage (install, uninstall, update, and so on) APT packages---assuming you know the name of the program you wish to install. Many Linux users prefer monitoring systems with something a little flashier than the original top program, such as htop. To download and install the latter program, start by running the following: mike\@server:\~\$ sudo apt-get update Have APT update its package index, the list of all the available packages (software). You can technically skip this step, but you might end up installing an old version or, if the package is new enough, not finding it. Once APT's index has been updated, run this next: mike\@server:\~\$ sudo apt-get install htop That's it! Got htop already installed but want the newest version? No problem! Just use **apt-get** again: mike\@server:\~\$ sudo apt-get upgrade htop The only downside to apt-get is that you need to know the name of the package you want to install. While there are command-line tools that help (apt-cache), many people prefer to use the graphical search tool their Linux distro provides, such as the Ubuntu Software Center. As useful as APT is for fetching and installing single applications, that's not where its real power lies. System package managers can manage all the software (minus anything you compiled yourself ) on the system; they are what you use to keep the whole system up to date, just as Windows Update handles much of the software on Windows. All that it takes to upgrade all the packages on your system is to run mike\@server:\~\$ sudo apt-get update mike\@server:\~\$ sudo apt-get upgrade If apt-get finds any out-of-date packages, it will let you know which ones and ask you to confirm the upgrade, then away it goes to download and update your system. Keeping your system up to date in this way is critical to close any security vulnerabilities that might be lurking on your system. For Red Hat--based systems (such as Fedora and CentOS), we use Red Hat Package Manager (RPM). As with APT, there's a convenient command line you can use to manage RPM packages: the yum command. There a lot of little differences between these package managers and the commands for working with them, but the essentials are virtually the same as with apt-get. Here are the commands we used to install htop, but for yum: mike\@server:\~\$ sudo yum update mike\@server:\~\$ sudo yum install htop **nano** the current CompTIA A+ 1102 objectives now focus on an easier-tolearn editor: GNU nano. You'll still find nano on most UNIXes, but it is a little less common than vi---tuck the name vi away in your pocket in case you need to edit a file on a system without nano! Let's get started with nano by creating a new text file called "fred" (the same command will also edit an existing file): mike\@server:\~\$ nano fred You'll now be in the nano text editor, staring at a blank file, The big thing to notice here is at the bottom of the screen, where nano lists a few important keyboard shortcuts (each prefixed with \^ to indicate that you should press ctrl and the indicated key simultaneously). The most important ones are in the bottom-left corner: Get Help, and Exit. Press ctrl + g once to access the help menu, and ctrl + x once to return to the edit view. To make basic edits in nano, all you need to do is move your cursor around with your keyboard and type or delete as needed. Enter a few lines of text, press enter at the end of each line, and use the backspace key if you make an error. To save your new file and quit nano, press ctrl + x. If you exit with unsaved changes (a "modified buffer"), nano will prompt you to save them, discard them, or cancel and return to the editor. Just press y to save the changes. It's important to know how to use a common editor such as nano or vi, but for day-to-day work most UNIX people usually reach for one of the hundreds of alternatives. Check out other terminal-based editors such as vim, joe, or emacs, and graphical editors such as gedit or gVim. **dd** The dd command is primarily used to create an exact, bit-by-bit image of any form of block storage, meaning mass storage devices such as hard drive volumes, thumb drives, and optical media. In its most simple form, the dd command is just \$ dd if=\ of=\ There's no way to show you all the possible uses for dd, so I'll just show three of the typical places I use it. Let's start with something simple: copying a hard drive. Be careful here---some people joke that dd stands for "Disk Destroyer" for a reason! This powerful tool will wreak havoc on your data if not used correctly. There are a number of issues that I'm not covering here that could greatly affect the success of running the dd command. While all of the following commands are valid, simply running them on your systems without understanding these subtleties can wipe drives. You have been warned! **Copying a Hard Drive** Let's say you have a hard drive (sda) you want to copy onto another hard drive (sdb). In this case we will say they are exactly the same size. The following command will copy the entire sda drive, partition table, file systems... everything to the sdb drive: dd if=/dev/sda of=/dev/sdb **Backing Up a Thumb Drive** Let's say you have thumb drive full of important files you really want to back up. Using dd as follows, you can copy the entire USB drive and make an image file (I chose to call it thumbBackup.bak) and place that image file on your Desktop: dd if=/dev/sdc of=/home/mike/Desktop/thumbBackup.bak **Wiping a Disk** I have a drive (sdb) that I want to totally wipe. The dd command can take input from anywhere, but in this case I'll use Linux's random number generator, /dev/urandom, to write a stream of random bits completely over the entire drive. It's not a perfect wipe, but it will stop all but the most sophisticated tools. dd if=/dev/urandom of=/dev/sdb **df** The df (display free disk space) command makes it easy to diagnose the most common storage-space issues on UNIX systems. You can just run **df** by itself, but I always run **df -h** (the -h switch uses human-friendly units): \$ df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 1.6G 0 1.6G 0% /dev tmpfs 16G 425M 16G 3% /dev/shm tmpfs 7.9G 6.7M 7.9G 1% /run tmpfs 16G 504K 16G 1% /run/wrappers /dev/nvme0n1p1 500M 140M 361M 28% /boot tmpfs 3.2G 92K 3.2G 1% /run/user/1000 One quick command is all I need to know that the primary volume (mounted at the root directory /) is about 83% full. **shutdown** In Windows, you can shut down or restart the system from a terminal using the shutdown command. Run the command as follows: shutdown \ \ By far the most common time is now. To shut down the system immediately, run shutdown now To restart the system, run **shutdown** with the **-r** option: shutdown -r now **Scripting** Up until now, we've entered commands into the CLI one by one. Most of the time all you need is one or two commands, but sometimes you will find yourself running the same series of commands to perform a task over and over. When you find yourself in this situation, it might be a good idea to write a script---a small program that helps automate a task by collecting a series of commands and giving them a name. Early in the chapter---when we looked at shells---I pointed out that a shell is the command-line interpreter that interprets the commands you run. It's time to let you in on a secret. Shells can also execute a text file by interpreting each line as if it were a command you typed and ran. We call these text files shell scripts. Each command shell has its own shell scripting language---and all of the commands I've shown you so far use a little slice of it. The rest of each shell's scripting language is for controlling when and how the shell runs the commands in a script---but you can make a super simple shell script by just copying a few shell commands to a new file and saving it. Imagine you have an application (importantapp.exe) that requires a weekly maintenance restart, where you run the following commands: kill /IM importantapp.exe /P gudpwd1 (shut down the application) cd \\ProgramData\\importantapp\\Data (Go to a specific location) del \*.tmp (delete the temporary files) copy config.ini config.bak /Y (back up config; overwrites last week\'s backup) importantapp.exe (start the application) **Script Types and Languages** Scripting is a kind of programming; a scripting language is a type of programming language for writing scripts. As with any kind of programming, there are many different scripting languages designed for a variety of purposes. The CompTIA A+ objectives expect you to be able to identify the file types for six different scripting languages. Table 15-1 lists and describes common scripting languages and their file extensions. A screenshot of a computer Description automatically generated **Ask Not What You Can Do for Scripting** The closest you can get is knowing the basic capabilities of scripting, seeing how other people like to automate, and building habits that make it easier to automate when the time comes. **Use Cases for Scripting** **Basic Automation** Basic automation is all about writing small scripts for tasks you perform regularly. These scripts save time and reduce errors in daily, weekly, or monthly tasks. **Restarting Machines** Just as \"Have you tried turning it off and back on?\" is a key troubleshooting step, automation for restarting machines is common. Nightly or weekend reboots ensure workstations are fresh for the next use. For laptops, scripts might offer warnings or flexible scheduling, while server scripts securely handle workloads, confirming backup systems are ready before a reboot. **Remapping Network Drives** Scripts commonly map network shares to drive letters, ensuring users can access necessary files from file servers. These scripts configure network shares accurately every time a user logs in, either universally or tailored to department-specific needs. **Installation of Applications** Scripts automate installing required applications on user systems, ensuring consistency and efficiency. They handle new setups and updates across multiple devices without manual intervention on each machine. **Automated Backups** While manual backups can suffice in some cases, automated backups are crucial for critical systems. Scripts ensure data is backed up reliably and regularly, minimizing potential data loss due to disasters, hardware failures, or erroneous updates. **Gathering of Information/Data** System administrators often need detailed reports on systems, whether it\'s diagnosing a crashing device or auditing a potentially compromised system. Scripts facilitate consistent and comprehensive data collection, whether on a single device or across a network. **Initiating Updates** Timely updates are crucial for security, but hasty updates can disrupt workflows. Scripts manage the update process, enabling controlled rollouts and minimizing risks of installing problematic updates. They allow phased deployments to catch incompatibilities early before widespread adoption. **Automatic Habits** **Automatic Habits** An all-too-common automation tragedy occurs when you repeatedly fix something manually, only to encounter roadblocks when trying to automate it. This leads to frustration and abandoning the script. To succeed in automating complex tasks, develop habits that give you a head start and automate gradually. **Notetaking Habits** Keep detailed notes, save command-line history and logs, organize them in a sensible way, refer back to them, and update them as needed. Good notes will answer crucial questions and save time when automating tasks. **Recognizing Automation Opportunities** Identify tasks that could benefit from a script. Signs include frequently flipping through command history to rerun commands or repeatedly checking notes or search engines to remember steps and their order. **Gradual Automation** Begin automating easy parts of a task, and gradually tackle more complex aspects. This approach helps avoid two common pitfalls: \- Investing significant effort into a script that is never used. \- Striving for perfection at the expense of progress. While fully automating a task is rewarding, it's better to start saving time and energy now. **Here Be Dragons** Before sending you off with just a text editor and a shell, there are hard truths: scripting can be dangerous and frustrating despite its power. Scripts are often fragile, sensitive to system differences unless anticipated. If a script assumes something is present (like a directory or command), and it\'s not, problems arise. The best scripts stop, reverse changes, and notify you of issues; many do not, requiring manual fixes and cleanup. **For the CompTIA A+ 1102 exam, consider these:** **Software Installation:** Scripts can install software from the command line. Running unverified scripts can unintentionally introduce malware. \- **Changing Settings:** Scripts can modify system settings. Malicious scripts may ease system compromise, and errors can inadvertently change settings. \- **Stability Issues:** Although uncommon, scripts can cause system or application instability---consider them as small programs capable of crashes from resource mishandling. To mitigate these risks, exercise caution and diligence. Educate users about avoiding untrusted scripts. Always read scripts before execution. Test scripts on non-critical systems first, and back up systems beforehand. Trial new scripts on a subset of systems prior to full deployment.