### Open Files with Registered Applications in Cygwin Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Use `cygstart` to open arbitrary files in Cygwin, which will launch them with their default registered Windows applications, similar to the `start` command in Windows or `open` on macOS. ```Shell cygstart document.docx ``` ```Shell cygstart http://www.example.com ``` -------------------------------- ### Package Management Commands Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Covers various package managers across different Linux distributions (`apt-get`, `yum`, `dnf`, `pacman`) for installing software. It also includes `pip` for Python package installation. ```Bash sudo apt-get update sudo apt-get install htop sudo yum install htop sudo dnf install htop sudo pacman -S htop pip install requests ``` -------------------------------- ### Install Programs with Cygwin Package Manager Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Install additional Unix programs within the Cygwin environment using its dedicated package manager, similar to `apt` or `yum` on Linux. ```Shell setup-x86_64.exe -q -P wget,curl # Example using Cygwin setup program ``` ```Shell apt-cyg install nano # Example using apt-cyg wrapper ``` -------------------------------- ### Getting Help for Bash Builtins and Command Type Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explains how to get help for Bash built-in commands using `help` and `help -d`. It also shows how to determine if a command is an executable, a built-in, or an alias using the `type` command. ```Bash help builtin_command help -d builtin_command type command_name ``` -------------------------------- ### Get macOS Release Information Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Use the `sw_vers` command to retrieve details about the currently installed macOS version, including product name, version, and build number. ```Shell sw_vers ``` -------------------------------- ### Leveraging /proc Filesystem for Live Debugging Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet highlights the utility of the `/proc` filesystem for live system debugging. It provides a virtual interface to kernel data structures, offering insights into processes and system hardware. Examples include `cpuinfo`, `meminfo`, `cmdline`, and process-specific directories like `cwd`, `exe`, `fd`, and `smaps`. ```Shell cat /proc/cpuinfo cat /proc/meminfo cat /proc/cmdline ls -l /proc//cwd ls -l /proc//exe ls -l /proc//fd/ cat /proc//smaps ``` -------------------------------- ### Rename files and contents using repren and rename Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Provides examples for using `repren` to perform full renaming of filenames, directories, and contents, and for recovering backup files. Also includes an alternative using the `rename` command for similar tasks. ```sh # Full rename of filenames, directories, and contents foo -> bar: repren --full --preserve-case --from foo --to bar . ``` ```sh # Recover backup files whatever.bak -> whatever: repren --renames --from '(.*)\.bak' --to '\1' *.bak ``` ```sh # Same as above, using rename, if available: rename 's/\.bak$//' *.bak ``` -------------------------------- ### Manage Packages on macOS with Homebrew and MacPorts Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Utilize `brew` (Homebrew) or `port` (MacPorts) for installing various command-line tools and applications on macOS, similar to package managers on Linux. ```Shell brew install package_name ``` ```Shell port install package_name ``` -------------------------------- ### Use Python Interpreter for Basic Calculations Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This example demonstrates how to leverage the Python interpreter interactively to perform basic arithmetic operations. It provides a quick and accessible way to use Python as a simple command-line calculator. ```Python >>> 2+3 5 ``` -------------------------------- ### Accessing Command Cheat Sheets with curl Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates how to use `curl` to quickly retrieve a cheat sheet for any shell command from `cheat.sh`. This provides a concise way to get common usage examples. ```Shell curl cheat.sh/ls ``` -------------------------------- ### Bash: Using xargs for Command Execution Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Leverage the powerful 'xargs' utility to build and execute command lines from standard input. Examples demonstrate finding files and piping them to grep, and using SSH on a list of hosts with placeholder substitution. ```bash find . -name '*.py' | xargs grep some_function ``` ```bash cat hosts | xargs -I{} ssh root@{} hostname ``` -------------------------------- ### Optimize SSH Client Configuration (~/.ssh/config) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Provides an example of an optimized ~/.ssh/config file. These settings help prevent dropped connections, enable compression for low-bandwidth scenarios, and multiplex channels to the same server, improving SSH session reliability and performance. ```ssh_config TCPKeepAlive=yes ServerAliveInterval=15 ServerAliveCountMax=6 Compression=yes ControlMaster auto ControlPath /tmp/%r@%h:%p ControlPersist yes ``` -------------------------------- ### Comparing and Summarizing Directory Changes with `diff` and `diffstat` Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Shows how to recursively compare two directories using `diff -r` and then pipe the output to `diffstat` to get a summary of the changes. ```sh diff -r tree1 tree2 | diffstat ``` -------------------------------- ### Bash: Persistent Configuration with .bashrc and .bash_profile Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Store your aliases, shell settings, and functions in '~/.bashrc' for interactive shell sessions. For commands that should run only upon login, use '~/.bash_profile'. Ensure these files are sourced correctly for your setup. ```bash ~/.bashrc ``` -------------------------------- ### Using sponge for in-place file modification Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates how to use the `sponge` command to read all input before writing it, which is particularly useful for modifying a file in-place. This example shows filtering lines from 'some-file' using `grep` and writing the output back to the same file. ```Shell grep -v something some-file | sponge some-file ``` -------------------------------- ### Converting Text Encodings and Manipulating Unicode with `uconv` Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Provides examples of using `uconv` for advanced Unicode text processing, such as displaying hex codes or character names, and performing operations like lowercasing and accent removal. ```sh # Displays hex codes or actual names of characters (useful for debugging): uconv -f utf-8 -t utf-8 -x '::Any-Hex;' < input.txt uconv -f utf-8 -t utf-8 -x '::Any-Name;' < input.txt # Lowercase and removes all accents (by expanding and dropping them): uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC;' < input.txt > output.txt ``` -------------------------------- ### Understand BSD vs. GNU Command Variations on macOS Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Be aware that many common Unix commands like `ps`, `ls`, `tail`, `awk`, and `sed` on macOS are BSD-based and may have subtle differences from their GNU counterparts found on Linux. For cross-platform scripts, consider using `gawk` or `gsed` if GNU versions are installed, or alternative languages like Python/Perl. ```Shell man ps # Check for 'BSD General Commands Manual' in the man page ``` ```Shell gawk '{print $1}' file.txt # Example of using GNU awk if installed ``` -------------------------------- ### Linux: Send Signals to Processes Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Control processes by sending specific signals. For example, 'kill -STOP [pid]' suspends a process. Refer to 'man 7 signal' for a comprehensive list of available signals and their effects. ```bash kill -STOP [pid] ``` -------------------------------- ### Get Octal File Permissions with stat (Shell) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Illustrates how to use the stat command with specific formatting options to retrieve file permissions in octal form. This is particularly useful for system configuration tasks where octal permissions are required and ls doesn't directly provide them. ```sh stat -c '%A %a %n' /etc/timezone ``` -------------------------------- ### Define Shell Function to Get Random Tip from Markdown Document Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This shell function, `taocl()`, fetches a Markdown document from a URL, processes it, and extracts a random tip. It uses `curl` to download, `sed` to filter, `pandoc` to convert Markdown to HTML, `xmlstarlet` for HTML parsing and selection, and `fmt`/`iconv` for formatting. The function demonstrates complex text processing and web content manipulation within a shell script. ```sh function taocl() { curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | sed '/cowsay[.]png/d' | pandoc -f markdown -t html | xmlstarlet fo --html --dropdtd | xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" | xmlstarlet unesc | fmt -80 | iconv -t US } ``` -------------------------------- ### Bash: Line Editing Keybindings Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Master Bash line editing with these keybindings. 'ctrl-w' deletes the last word, 'ctrl-u' clears the line from the cursor to the start, 'alt-b' and 'alt-f' move by word, 'ctrl-a' and 'ctrl-e' move to line start/end, 'ctrl-k' deletes to the end, and 'ctrl-l' clears the screen. ```bash ctrl-w ``` ```bash ctrl-u ``` ```bash alt-b ``` ```bash alt-f ``` ```bash ctrl-a ``` ```bash ctrl-e ``` ```bash ctrl-k ``` ```bash ctrl-l ``` -------------------------------- ### Introduction to Version Control with Git Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Recommends learning a version control system like Git and provides basic commands for initializing a repository, staging changes, and committing them. ```Git git init git add . git commit -m "First commit" ``` -------------------------------- ### Finding Manual Pages with man and apropos Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Details how to use `man` to read documentation and `apropos` to search for man pages by keyword. It also explains the section numbers in man pages. ```Bash man man apropos keyword ``` -------------------------------- ### Serve Files with Python HTTP Server Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet demonstrates how to quickly set up a simple HTTP server using Python's built-in modules. It serves files from the current directory and its subdirectories, accessible to anyone on the network. Commands are provided for both Python 2 and Python 3. ```Python python -m SimpleHTTPServer 7777 ``` ```Python python -m http.server 7777 ``` -------------------------------- ### Monitoring CPU and Disk Status with Linux Tools Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet outlines command-line utilities for monitoring system CPU and disk I/O. `top` and `htop` provide real-time process and resource usage. `iostat` and `iotop` focus on disk I/O statistics. `iostat -mxz 15` specifically provides detailed CPU and per-partition disk stats every 15 seconds. ```Shell top htop iostat iotop iostat -mxz 15 ``` -------------------------------- ### Unix-like Environments for Windows Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explore various methods to bring Unix command-line capabilities to Windows, including full environments like Cygwin and WSL, or more focused toolsets like MinGW/MSYS and Cash. ```APIDOC Cygwin: Description: Provides a comprehensive Unix-like environment on Windows. Features: Most Unix tools work out-of-the-box. Link: https://cygwin.com/ ``` ```APIDOC Windows Subsystem for Linux (WSL): Description: Offers a native Bash environment with Unix utilities on Windows 10+. Features: Familiar Bash environment, direct access to Windows files. Link: https://learn.microsoft.com/en-us/windows/wsl/ ``` ```APIDOC MinGW / MSYS: Description: MinGW provides GNU developer tools (e.g., GCC), and MSYS offers utilities like bash, gawk, make, grep. Features: Useful for creating native Windows ports of Unix tools. Limitations: Fewer features compared to Cygwin. Links: http://www.mingw.org/, http://www.mingw.org/wiki/msys ``` ```APIDOC Cash: Description: A JavaScript-based shell for Windows. Features: Provides a Unix-like feel. Limitations: Very few Unix commands and options available. Link: https://github.com/dthree/cash ``` -------------------------------- ### SSH and Passwordless Authentication Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explains the basics of `ssh` for remote access and setting up passwordless authentication using `ssh-agent` and `ssh-add` for managing SSH keys. ```Shell ssh user@hostname ssh-agent bash ssh-add ~/.ssh/id_rsa ``` -------------------------------- ### Web Server Performance Testing with AB and Siege Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet introduces tools for web server performance testing. `ab` (ApacheBench) is a simple command-line tool for quick load testing and benchmarking HTTP servers. `siege` is a more robust and feature-rich HTTP load testing and benchmarking utility for more complex scenarios. ```Shell ab -n 100 -c 10 http://example.com/ siege http://example.com/ ``` -------------------------------- ### Copy stdin to file and stdout using tee Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Illustrates the use of the `tee` command to copy standard input to both a specified file and standard output simultaneously. ```sh ls -al | tee file.txt ``` -------------------------------- ### System Overview with Dstat and Glances Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet introduces tools for a comprehensive system overview. `dstat` provides a versatile real-time display of system resources. `glances` offers a broader, more detailed overview of system activity, including CPU, memory, disk I/O, and network. ```Shell dstat glances ``` -------------------------------- ### Use mintty as Cygwin Command-Line Window Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md It is recommended to use `mintty` as the terminal emulator for Cygwin, offering a more feature-rich and user-friendly experience compared to the default Windows console. ```Shell mintty.exe - ``` -------------------------------- ### Accessing Bash Manual Page Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explains how to access the manual page for Bash, which is essential for understanding its capabilities. It emphasizes the importance of reading documentation. ```Bash man bash ``` -------------------------------- ### Fetch and Process Command Line Terms with cowsay Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This command fetches the README.md file from a GitHub repository, extracts all words enclosed in backticks (which typically represent command-line terms), removes the backticks, and then pipes the result to `cowsay` to display them in an ASCII cow bubble. It demonstrates chaining multiple Unix commands for text processing and fun. ```Bash curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50 ``` -------------------------------- ### Basic File and Filesystem Management Commands Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Provides a comprehensive list of essential commands for managing files and filesystems, including listing, viewing, linking (hard and soft), changing ownership and permissions, checking disk usage, and managing partitions and block devices. It also covers inode inspection. ```Bash ls ls -l less filename.txt head filename.txt tail filename.txt tail -f filename.txt ln original_file hard_link ln -s original_file symbolic_link chown newuser:newgroup filename.txt chmod 755 filename.txt du -hs * df -h mount /dev/sdb1 /mnt/data fdisk -l mkfs.ext4 /dev/sdb1 lsblk ls -i filename.txt df -i ``` -------------------------------- ### Locate files by name Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates how to find files by name in the current directory using `find` or globally using `locate`. `locate` relies on a pre-indexed database and may not reflect recently created files. ```sh find . -iname '*something*' ``` ```sh locate something ``` -------------------------------- ### Pretty-print and Diff Two JSON Files with jq, colordiff, and less Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This command line one-liner pretty-prints two JSON files (`file1.json`, `file2.json`) by normalizing their keys using `jq --sort-keys`. The output is then piped to `diff`, colored with `colordiff`, and paginated for easy viewing with `less -R`. This is useful for comparing configuration files or API responses. ```sh diff <(jq --sort-keys . < file1.json) <(jq --sort-keys . < file2.json) | colordiff | less -R ``` -------------------------------- ### Basic Network Management Commands Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Lists fundamental commands for network configuration and troubleshooting, such as `ip` (or `ifconfig`) for interface details, `dig` for DNS lookups, `traceroute` for path tracing, and `route` for routing table inspection. ```Bash ip addr show ifconfig dig google.com traceroute google.com route -n ``` -------------------------------- ### Search Files and View Metadata with macOS Spotlight Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Perform file searches using `mdfind` which leverages the macOS Spotlight index. Use `mdls` to list metadata attributes of files, such as EXIF information for photos. ```Shell mdfind "kind:image created:today" ``` ```Shell mdls photo.jpg ``` -------------------------------- ### Linux: Check System Uptime and Users Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Determine how long your system has been running and who is logged in. 'uptime' provides a concise summary, while 'w' shows currently logged-in users and their activity. ```bash uptime ``` ```bash w ``` -------------------------------- ### Extracting Keywords from README with Curl and Grep Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README-ko.md This command demonstrates how to fetch the README content from GitHub using `curl`, extract words enclosed in backticks using `egrep` with a regular expression, remove the backticks with `tr`, and then pipe the processed output to `cowsay` for a whimsical display. It showcases basic command-line chaining and text processing. ```Shell curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '\`\\w+\`' | tr -d '\`' | cowsay -W50 ``` -------------------------------- ### Compare Files Using Process Substitution (Shell) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Shows how process substitution (<(command)) allows the output of a command to be treated as a file. This is highly useful for commands like diff that expect file paths as arguments, enabling comparisons between command outputs or remote files. ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -------------------------------- ### Identifying Operating System Information Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet provides commands to identify operating system details. `uname` or `uname -a` displays general Unix/kernel information. `lsb_release -a` (if available) provides more specific Linux distribution information. ```Shell uname uname -a lsb_release -a ``` -------------------------------- ### Bash: Directory Navigation Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Navigate the file system efficiently in Bash. Use 'cd' to go to your home directory, '~' to reference paths relative to home, and '$HOME' in scripts. 'cd -' returns to the previous working directory. ```bash cd ``` ```bash ~/.bashrc ``` ```bash $HOME ``` ```bash cd - ``` -------------------------------- ### Convert HTML to text using lynx Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Converts HTML content from standard input to plain text using the `lynx` browser in dump mode. ```sh lynx -dump -stdin ``` -------------------------------- ### Saving and Restoring File Permissions with ACLs using `getfacl` and `setfacl` Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Shows how to back up Access Control Lists (ACLs) for a directory tree using `getfacl` and then restore them to another location or after a system change using `setfacl`. ```sh getfacl -R /some/path > permissions.txt setfacl --restore=permissions.txt ``` -------------------------------- ### Utilize Native Windows Command-Line Networking Tools Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Access essential networking utilities built into Windows, such as `ping` for connectivity testing, `ipconfig` for network configuration, `tracert` for route tracing, and `netstat` for network connection statistics. ```Windows Command Prompt ping google.com ``` ```Windows Command Prompt ipconfig /all ``` ```Windows Command Prompt tracert 8.8.8.8 ``` ```Windows Command Prompt netstat -an ``` -------------------------------- ### Using grep and Regular Expressions Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Highlights the importance of regular expressions and demonstrates common `grep` options for case-insensitive search (`-i`), showing only matches (`-o`), inverting matches (`-v`), and displaying context lines (`-A`, `-B`, `-C`). ```Bash grep -i "error" log.txt grep -o "pattern" file.txt grep -v "info" log.txt grep -A 2 "warning" log.txt grep -B 2 "warning" log.txt grep -C 2 "warning" log.txt ``` -------------------------------- ### Monitoring Network Bandwidth Usage Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet describes tools for monitoring network bandwidth usage per process or socket. `iftop` displays bandwidth usage on an interface, showing connections and their speeds. `nethogs` groups bandwidth by process, making it easy to identify which applications are consuming network resources. ```Shell iftop nethogs ``` -------------------------------- ### Formatting Current Date and Time in ISO 8601 Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates how to use the `date` command to output the current UTC date and time in the ISO 8601 format, which is useful for consistent timestamping. ```sh date -u +"%Y-%m-%dT%H:%M:%SZ" ``` -------------------------------- ### Sorting Files with the `sort` Command Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates how to use the `sort` command with advanced options, including key-based sorting (`-k`) and stable sorting (`-s`), to sort data based on multiple fields. ```sh sort -k1,1 | sort -s -k2,2 ``` -------------------------------- ### Perform Windows System Administration with WMIC Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md The `wmic` command-line utility allows users to perform and script a wide range of Windows system administration tasks, leveraging Windows Management Instrumentation. ```Windows Command Prompt wmic os get Caption,CSDVersion ``` ```Windows Command Prompt wmic process get Name,ProcessId ``` -------------------------------- ### Linux/macOS: List Listening Network Processes Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Identify processes listening on network ports. 'netstat -lntp' and 'ss -plat' (for TCP, add -u for UDP) are common Linux tools. 'lsof -iTCP -sTCP:LISTEN -P -n' works across Linux and macOS, showing open files and network connections. ```bash netstat -lntp ``` ```bash ss -plat ``` ```bash lsof -iTCP -sTCP:LISTEN -P -n ``` -------------------------------- ### Inspecting Network Connections with Netstat and SS Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet details tools for viewing active network connections, routing tables, and interface statistics. `netstat` is a traditional utility, while `ss` is a newer, faster alternative for displaying socket statistics. ```Shell netstat ss ``` -------------------------------- ### Understanding I/O Redirection and Pipes in Bash Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explains the use of `>` for output redirection (overwrite), `>>` for appending, `<` for input redirection, and `|` for piping output of one command to another. It also mentions `stdout` and `stderr`. ```Bash echo "Hello" > file.txt echo "World" >> file.txt cat < file.txt ls -l | grep .txt ``` -------------------------------- ### Optimize sorting performance by setting LC_ALL Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explains how setting the `LC_ALL` environment variable to `C` can significantly improve the performance of commands like `sort` by forcing byte-based collation and bypassing slower internationalization routines. ```sh export LC_ALL=C ``` -------------------------------- ### Analyzing Historic System Performance with Sar Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet introduces `sar` (System Activity Reporter), a tool for collecting, reporting, and saving system activity information. It's invaluable for post-mortem analysis, providing historical statistics on CPU utilization, memory, network I/O, and other system resources. ```Shell sar sar -u 1 5 ``` -------------------------------- ### Use Here Documents for Multi-Line Input (Shell) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates the 'here document' feature, which allows redirection of multiple lines of input to a command as if they were coming from a file. This is useful for providing large blocks of text or configuration to commands like cat or ssh. ```sh cat < jps jstat jstack jmap ``` -------------------------------- ### Linux: Inspect Open Sockets and Files Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Use 'lsof' and 'fuser' to inspect open files and sockets on your system. These utilities help identify which processes are using specific files or network connections. ```bash lsof ``` ```bash fuser ``` -------------------------------- ### Convert Markdown to Word using pandoc Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Illustrates how to convert a Markdown document (`README.md`) to a Word (`.docx`) format using `pandoc`. ```sh pandoc README.md --from markdown --to docx -o temp.docx ``` -------------------------------- ### Access Encoding Information via Man Pages (Shell) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Lists useful man commands for accessing documentation related to character encodings. These commands provide detailed information on ASCII, Unicode, UTF-8, and Latin-1, which is helpful for understanding character sets and their representations. ```sh man ascii ``` ```sh man unicode ``` ```sh man utf-8 ``` ```sh man latin1 ``` -------------------------------- ### Tracing System Calls and Library Calls with Strace and Ltrace Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet describes `strace` and `ltrace`, powerful debugging tools for tracing program execution. `strace` monitors system calls made by a process, while `ltrace` traces library calls. They are invaluable for diagnosing program failures, hangs, or performance issues, offering options for profiling (`-c`), attaching to running processes (`-p`), and tracing child processes (`-f`). ```Shell strace strace -p strace -c strace -f ltrace ``` -------------------------------- ### Advanced System and Performance Analysis Tools Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet lists advanced tools for in-depth system and performance analysis. `SystemTap` allows dynamic instrumentation of a running Linux kernel. `perf` is a Linux profiling tool. `sysdig` is a system exploration and troubleshooting tool that captures system calls and events. ```Shell stap perf top sysdig ``` -------------------------------- ### List File Sizes and Dates Recursively using find -ls Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This command provides a recursive listing of files, similar to `ls -lR`, but often more readable. It uses `find . -type f` to locate all regular files in the current directory and its subdirectories. The `-ls` action then prints detailed information for each found file, including inode number, block count, permissions, number of hard links, owner, group, size, and modification time. ```sh find . -type f -ls ``` -------------------------------- ### Open Files with Desktop Apps on macOS Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md The `open` command allows you to open files using their default associated desktop applications on macOS. You can also specify a particular application using the `-a` flag. ```Shell open document.pdf ``` ```Shell open -a /Applications/Google\ Chrome.app index.html ``` -------------------------------- ### Bash Job Management Commands Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Introduces fundamental commands for managing processes in Bash, including running commands in the background (`&`), pausing (`ctrl-z`), terminating (`ctrl-c`), listing jobs (`jobs`), bringing to foreground (`fg`), sending to background (`bg`), and killing processes by PID (`kill`). ```Bash sleep 100 & jobs fg %1 bg %1 kill PID ``` -------------------------------- ### Copy and Paste with macOS Clipboard Commands Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Use `pbcopy` to pipe command output directly to the macOS clipboard and `pbpaste` to retrieve clipboard content as input for commands. ```Shell echo "Hello World" | pbcopy ``` ```Shell pbpaste > clipboard_content.txt ``` -------------------------------- ### Bash Variable and Arithmetic Expansions Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Illustrates various forms of variable expansion in Bash, including checking for variable existence, setting default values, performing arithmetic operations, generating sequences, and trimming strings. These expansions provide powerful ways to manipulate and use variables in scripts. ```bash input_file=${1:?usage: $0 input_file} ``` ```bash output_file=${2:-logfile} ``` ```bash i=$(( (i + 1) % 5 )) ``` ```bash {1..10} ``` ```bash echo ${var%.pdf}.txt ``` -------------------------------- ### Access Windows Registry from Cygwin Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md The `regtool` utility provides command-line access to the Windows Registry from within the Cygwin environment, allowing for scripting and automation of registry modifications. ```Shell regtool list /HKCU/Software/Microsoft ``` ```Shell regtool get /HKLM/SOFTWARE/Microsoft/Windows\ NT/CurrentVersion/ProductName ``` -------------------------------- ### Switch Shell Session to Another User with Su Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet details the `su` command, used for switching the current shell session to another user. `su username` changes the user while retaining the current environment, whereas `su - username` provides a clean environment as if the user just logged in. Omitting the username defaults to switching to root, and the command requires the password of the target user. ```Shell su username ``` ```Shell su - username ``` ```Shell su ``` -------------------------------- ### Linux: Find and Signal Processes by Name Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Efficiently find and send signals to processes based on their name. 'pgrep' finds process IDs, and 'pkill' sends a signal (e.g., terminate) to processes matching a name. The '-f' option is useful for full command line matching. ```bash pgrep ``` ```bash pkill ``` -------------------------------- ### Linux: Display Process Tree Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md View the hierarchical structure of running processes on a Linux system. The 'pstree -p' command displays processes in a tree format, including their Process IDs (PIDs). ```bash pstree -p ``` -------------------------------- ### Network Path Diagnosis with MTR Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet introduces `mtr`, a network diagnostic tool that combines the functionality of `ping` and `traceroute`. It continuously probes network paths to identify latency and packet loss, providing a more comprehensive view of network issues. ```Shell mtr ``` -------------------------------- ### Efficiently delete large numbers of files using rsync Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates a fast and efficient method to delete a large number of files within a directory by synchronizing it with an empty directory using `rsync`. ```sh mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir ``` -------------------------------- ### Bash: Command Completion and History Search Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Utilize Bash keybindings for efficient command-line interaction. 'Tab' provides auto-completion and lists available commands, while 'ctrl-r' allows searching through command history, cycling through matches, and executing or editing found commands. ```bash Tab ``` ```bash ctrl-r ``` -------------------------------- ### Analyzing Disk Usage with Ncdu Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet highlights `ncdu`, a disk usage analyzer with a ncurses interface. It provides a quick and interactive way to navigate directories and identify large files or folders consuming disk space, offering a more efficient alternative to `du -sh *`. ```Shell ncdu ``` -------------------------------- ### Bash: Advanced Editing Keybindings Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explore advanced Bash keybindings for enhanced command-line productivity. 'alt-.' cycles through previous command arguments, and 'alt-*' expands a glob pattern, offering quick access to past inputs and file matching. ```bash alt-. ``` ```bash alt-* ``` -------------------------------- ### Reviewing Kernel Messages with Dmesg Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet introduces `dmesg`, a command that displays the kernel ring buffer messages. It's essential for diagnosing hardware issues, driver problems, or other low-level system anomalies that the kernel logs during boot or runtime. ```Shell dmesg ``` -------------------------------- ### Tally Occurrences of a Pattern in a Log File with egrep, cut, sort, uniq Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This pipeline extracts and tallies specific values, such as `acct_id` from a web server log (`access.log`). It uses `egrep -o` to find and output only the matching pattern, `cut` to isolate the ID, `sort` to group identical IDs, `uniq -c` to count occurrences, and finally `sort -rn` to display the results in descending order of count. This is useful for analyzing request patterns. ```sh egrep -o 'acct_id=[0-9]+' access.log | cut -d= -f2 | sort | uniq -c | sort -rn ``` -------------------------------- ### Access Windows Clipboard in Cygwin Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Interact with the Windows clipboard directly from the Cygwin environment by reading from or writing to the special device file `/dev/clipboard`. ```Shell cat /dev/clipboard ``` ```Shell echo "Text from Cygwin" > /dev/clipboard ``` -------------------------------- ### Checking Shared Libraries with LDD Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet introduces `ldd`, a utility to print shared library dependencies of executable files or shared libraries. It helps identify missing libraries or resolve linking issues. A critical warning is provided: never run `ldd` on untrusted files due to potential security risks. ```Shell ldd ``` -------------------------------- ### Execute Commands as Another User with Sudo Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This section explains how to use the `sudo` command to run commands with elevated privileges or as a different user. By default, `sudo` runs commands as root. The `-u` option allows specifying an alternative user, and `-i` can be used to log in as that user, requiring the current user's password. ```Shell sudo command_to_run ``` ```Shell sudo -u username command_to_run ``` ```Shell sudo -i ``` -------------------------------- ### Convert Paths Between Cygwin and Windows Styles Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md The `cygpath` utility is crucial for converting file paths between Cygwin's Unix-like format (`/cygdrive/c`) and Windows' native format (`C:\`). This is especially useful when scripting interactions between Cygwin and Windows programs. ```Shell cygpath -w /cygdrive/c/Users/Public/Documents # Convert Cygwin to Windows ``` ```Shell cygpath -u "C:\Program Files\Git" # Convert Windows to Cygwin ``` -------------------------------- ### Redirect Standard Output and Error (Bash) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Covers methods for redirecting both standard output and standard error to a single log file in Bash. It also highlights the good practice of redirecting standard input from /dev/null to prevent commands from tying to the terminal. ```bash some-command >logfile 2>&1 ``` ```bash some-command &>logfile ``` ```bash ``` -------------------------------- ### Invoke Windows Tasks with Rundll32 Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md The `Rundll32` command can be used to execute functions exported from 32-bit DLLs, enabling various system tasks and shortcuts from the command line. ```Windows Command Prompt Rundll32.exe shell32.dll,Control_RunDLL desk.cpl ``` ```Windows Command Prompt Rundll32.exe user32.dll,LockWorkStation ``` -------------------------------- ### Replace string in multiple files using Perl Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Replaces all occurrences of 'old-string' with 'new-string' in specified files (`my-files-*.txt`) in place, creating a `.bak` backup. ```sh perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt ``` -------------------------------- ### Security-Sensitive SSH Configuration Options Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Highlights two security-sensitive SSH configuration options: StrictHostKeyChecking=no and ForwardAgent=yes. It emphasizes that these should be enabled with extreme care, ideally only for specific subnets, hosts, or within trusted network environments due to their security implications. ```ssh_config StrictHostKeyChecking=no ``` ```ssh_config ForwardAgent=yes ``` -------------------------------- ### Setting Immutable File Attribute with `chattr` Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Illustrates how to use the `chattr` command to set the immutable flag (`+i`) on a file or directory, preventing accidental deletion or modification even by the root user. ```sh sudo chattr +i /critical/directory/or/file ``` -------------------------------- ### Perform Set Operations (Union, Intersection, Difference) on Text Files Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet demonstrates how to perform set union, intersection, and difference on two text files (`a` and `b`) using `sort` and `uniq`. It's efficient for large files as `sort` is not memory-limited. The output is redirected to file `c`. ```sh sort a b | uniq > c # c is a union b sort a b | uniq -d > c # c is a intersect b sort a b b | uniq -u > c # c is set difference a - b ``` -------------------------------- ### Set command-specific environment variables Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Shows how to temporarily set an environment variable, such as `TZ` for timezone, for a single command execution without affecting the global shell environment. ```sh TZ=Pacific/Fiji date ``` -------------------------------- ### Advanced Network Packet Analysis Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet lists powerful tools for in-depth network debugging and packet analysis. `Wireshark` is a graphical network protocol analyzer. `tshark` is its command-line counterpart. `ngrep` is a network grep tool that allows searching for patterns in network packets. ```Shell tshark ngrep ``` -------------------------------- ### Execute Commands in a Subshell (Bash) Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Demonstrates how to use subshells (parentheses) in Bash to group commands. This allows for temporary changes, such as navigating to a different directory, without affecting the parent shell's current working directory. ```bash (cd /some/other/dir && other-command) ``` -------------------------------- ### Checking Memory Status with Free and Vmstat Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet describes commands to inspect system memory usage. `free` displays the amount of free and used physical and swap memory. `vmstat` reports virtual memory statistics. Understanding the 'cached' value is crucial as it represents memory used by the kernel for file caching, which can be reclaimed. ```Shell free vmstat ``` -------------------------------- ### Bash: Create Command Aliases Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Define custom shortcuts for frequently used commands. The 'alias' command allows you to assign a shorter name to a longer command or sequence of commands, like 'alias ll='ls -latr'' for listing files. ```bash alias ll='ls -latr' ``` -------------------------------- ### Bash: Comment Out Current Command Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Quickly comment out a partially typed command in Bash to save it for later. Use 'alt-#' or the sequence 'ctrl-a', '#', 'enter' to prepend a '#' and turn the line into a comment, preserving it in history. ```bash alt-# ``` ```bash ctrl-a # enter ``` -------------------------------- ### Bash: Command History Management Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Manage and re-execute past commands in Bash. Use 'history' to view recent commands, '!n' to re-execute by number, '!$' for the last argument of the previous command, and '!!' for the last command executed. ```bash history ``` ```bash !n ``` ```bash !$ ``` ```bash !! ``` -------------------------------- ### Finding Deleted Files Still in Use by Processes Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This snippet addresses a common scenario where deleting a file doesn't immediately free up disk space. It provides a command using `lsof` to identify processes that still have a handle open to a deleted file, preventing its space from being reclaimed until the process releases it. ```Shell lsof | grep deleted | grep "filename-of-my-big-file" ``` -------------------------------- ### File Globbing and Quoting in Bash Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Covers file glob expansion using wildcards like `*`, `?`, and `[]`. It also differentiates between double quotes (`"`) and single quotes (`'`) for string literal interpretation and variable expansion. ```Bash ls *.txt echo "Hello $USER" echo 'Hello $USER' ``` -------------------------------- ### Encapsulate Bash Script Code in Curly Braces Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Advises wrapping entire Bash script code within curly braces. This practice ensures that if a script is partially downloaded, a missing closing brace will result in a syntax error, preventing incomplete or potentially malicious code from executing. ```bash { # Your code here } ``` -------------------------------- ### Inserting Tab Literals in Bash Command Line Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Explains how to insert a literal tab character in Bash, either by using the control-v sequence or the more portable ANSI C-style string syntax. ```sh $'\t' ``` -------------------------------- ### Bash: Switch to Vi or Emacs Keybindings Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Change your Bash command-line editing mode to either vi-style or emacs-style keybindings. Use 'set -o vi' to enable vi mode and 'set -o emacs' to revert to the default emacs mode. ```bash set -o vi ``` ```bash set -o emacs ``` -------------------------------- ### Sum Numbers in a Specific Column of a Text File using awk Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md This `awk` command efficiently sums all numerical values found in the third column of `myfile`. It iterates through each line, accumulating the value of the third field (`$3`) into variable `x`. After processing all lines, the final sum is printed. ```sh awk '{ x += $3 } END { print x }' myfile ``` -------------------------------- ### Bash: Keep Background Processes Running Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Ensure background processes continue to run even after the shell session ends. Use 'nohup' to prevent processes from being terminated when the controlling terminal closes, or 'disown' to remove a job from the shell's job table. ```bash nohup ``` ```bash disown ``` -------------------------------- ### Bash: Multi-line Command Editing Source: https://github.com/jlevy/the-art-of-command-line/blob/master/README.md Edit long Bash commands in an external editor for multi-line input. Set your preferred editor using 'export EDITOR=vim', then use 'ctrl-x ctrl-e' (Emacs style) or 'escape-v' (Vi style) to open the current command in the editor. ```bash export EDITOR=vim ``` ```bash ctrl-x ctrl-e ``` ```bash escape-v ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.