### For Loop Initialization Source: https://speedsheet.io/s/bash?q=control-only Examples of different ways to initialize or define the range for a 'for' loop. ```bash for ((value=0; value < max; value++)) ``` ```bash for value in {first..last} ``` ```bash for value in "${array_1[@]}" ``` ```bash for value in "value 1" "value 2" "value 3" ``` -------------------------------- ### Rsync with Identity File Source: https://speedsheet.io/s/bash Example of using rsync with a specified identity file for authentication. ```bash rsync -i identity_file_path ... ``` -------------------------------- ### Get CPU Details Source: https://speedsheet.io/s/bash Lists detailed information about the system's CPU. Requires the 'util-linux' package. ```bash lscpu ``` -------------------------------- ### Get PCI Device Details Source: https://speedsheet.io/s/bash Lists detailed information about the system's PCI devices. This command is part of the 'pciutils' package and may not be installed by default. ```bash lspci ``` -------------------------------- ### Example of Resetting Color Source: https://speedsheet.io/s/bash Shows how to apply a specific foreground color and then reset it using the defined escape sequence. ```bash echo "\e[93m Green \e[0m Reset" ``` -------------------------------- ### Get Host Name Source: https://speedsheet.io/s/bash Displays the system's network host name. ```bash hostname ``` ```bash hostnamectl ``` -------------------------------- ### Get Operating System Name Source: https://speedsheet.io/s/bash Returns the name of the Operating System. ```bash uname ``` -------------------------------- ### Get Bash Version Source: https://speedsheet.io/s/bash Retrieves the installed Bash version information. ```bash bash --version ``` ```bash echo $BASH_VERSION ``` ```bash echo ${BASH_VERSION%%[^0-9.]*} ``` -------------------------------- ### Set Prompt to Host Name and Current Path Source: https://speedsheet.io/s/bash Combines the hostname and the full current path in the prompt, separated by a colon. Example output: host-1:~/downloads> ```bash PS1="\h:\w>" ``` -------------------------------- ### Start a New Bash Shell Source: https://speedsheet.io/s/bash Initiates a new interactive Bash shell session. ```bash /usr/bin/env bash ``` ```bash /bin/bash ``` -------------------------------- ### Document Comment Example Source: https://speedsheet.io/s/bash?q=fundamentals-only Place documentation comments before functions to provide context. Use a single hash '#' before the descriptive text. ```bash # This is a doc comment. function_1() { ... } ``` ```bash # This is a doc comment. # Adds context to the # following function. function_1() { ... } ``` -------------------------------- ### Example of Resetting Background Color Source: https://speedsheet.io/s/bash Illustrates applying a specific background color and then resetting it to the default using the escape sequence. ```bash echo "\e[104m Light Blue Background \e[49m Reset" ``` -------------------------------- ### Get Running Shell Source: https://speedsheet.io/s/bash Identifies the currently active shell process. Example results include 'bash' or '-zsh'. ```bash ps -ocomm= $$ ``` -------------------------------- ### Example Usage of ANSI Colors Source: https://speedsheet.io/s/bash Demonstrates how to use predefined ANSI color variables to print text with specific foreground and background colors, followed by a reset. ```bash echo "${LIGHT_GREEN}${ON_DARK_GRAY} Prints Light Green on Dark Gray ${RESET_COLOR}" ``` -------------------------------- ### Example Usage of Variable Source: https://speedsheet.io/s/bash?q=variables-only Demonstrates how to use a variable within an echo command, ensuring proper quoting for values with spaces. ```bash text="Print this text." echo "$text" ``` -------------------------------- ### Get Operating System Details Source: https://speedsheet.io/s/bash Provides detailed information about the OS version. Multiple commands can be used to retrieve this information. ```bash hostnamectl ``` ```bash cat /etc/os-release ``` ```bash cat /etc/*-release ``` ```bash cat /proc/version ``` -------------------------------- ### Find Lines Starting With a String Source: https://speedsheet.io/s/bash?q=files-only Use the `look` command to retrieve lines from a file that begin with a specified prefix. ```bash look starting_with file_1 ``` ```bash look starting_with files ``` -------------------------------- ### Full Named Pipe Example Source: https://speedsheet.io/s/bash Demonstrates a complete inter-process communication scenario using named pipes. Terminal 1 creates the pipe and listens for input, while Terminal 2 sends data to it. ```bash mkfifo pipe-1 cat < pipe-1 ``` ```bash cat > pipe-1 Send this over the pipe. CTRL + D ``` ```bash rm pipe-1 ``` -------------------------------- ### Get File Information Source: https://speedsheet.io/s/bash?q=files-only Use the `file` command to determine the type and properties of a file, such as executable status, text content, and encoding. ```bash file file_name ``` -------------------------------- ### Get System IO Information Source: https://speedsheet.io/s/bash Displays I/O statistics and CPU usage over a specified length of time and count. ```bash iostat length count ``` -------------------------------- ### Get First 10 Lines of String Source: https://speedsheet.io/s/bash Returns the first 10 lines of a string using the `head` command. Pipe the string output to `head`. ```bash command | head ``` -------------------------------- ### Show Command Help Source: https://speedsheet.io/s/bash Displays the manual page for a given command, providing detailed usage information. Press 'Q' to exit. ```bash man command ``` -------------------------------- ### Slice a Bash array to get a subarray Source: https://speedsheet.io/s/bash?q=array-only Extracts a portion of an array defined by a starting index and a length. ```bash array_1=(1 2 3 4 5 6) array_2=("${array_1[@]:2:3}") # array_2 will contain (3 4 5) ``` -------------------------------- ### Get System Information Source: https://speedsheet.io/s/bash Displays system information, including free memory and CPU usage, over a specified length of time and count. ```bash vmstat length count ``` -------------------------------- ### Get all elements except the first from a Bash array Source: https://speedsheet.io/s/bash?q=array-only Returns a subarray containing all elements starting from the second element (index 1) to the end. ```bash array_1=("one" "two" "three") remainder=("${array_1[@]:1}") echo "${remainder[@]}" ``` -------------------------------- ### Create Directory Source: https://speedsheet.io/s/bash?q=files-only Creates a new directory with the specified name. ```bash mkdir directory ``` -------------------------------- ### View First 10 Lines of a File Source: https://speedsheet.io/s/bash?q=files-only Use `head` to display the initial 10 lines of a specified file. ```bash head file_name ``` -------------------------------- ### Basic 'Hello World' Script Source: https://speedsheet.io/s/bash A simple Bash script to print 'Hello world!' to the console. This is the most basic script to verify Bash execution. ```bash echo "Hello world!" ``` -------------------------------- ### Slice Bash Array from Start Source: https://speedsheet.io/s/bash Extracts a portion of a bash array starting from a specified index to the end. ```bash array_1=(1 2 3 4 5 6) array_2=("${array_1[@]:4}") ``` -------------------------------- ### Create Directory with Subdirectories Source: https://speedsheet.io/s/bash?q=files-only Creates a directory and any necessary parent directories that do not already exist. ```bash mkdir -p directory/directory/directory ``` -------------------------------- ### Bash Case Statement Execution Example Source: https://speedsheet.io/s/bash?q=case-only An example of a Bash case statement that executes commands based on a variable's value. ```bash command="start" case "$command": "start") echo "Starting" ;; "stop") echo "Stopping" ;; esac ``` -------------------------------- ### Extract Substring Using Bash Parameter Expansion Source: https://speedsheet.io/s/bash Extracts a portion of a string based on a starting position and length. The start position is 0-indexed. ```bash =${string_1:start:length} ``` ```bash string_1="012345" substring=${string_1:2:2} echo "$substring" ``` -------------------------------- ### Mirror Directory with rsync Source: https://speedsheet.io/s/bash?q=files-only Mirrors the contents of a source directory to a target directory using rsync, ensuring both directories are identical. Requires rsync to be installed. ```bash rsync -avE --delete source_directory/ target_parent_directory/ ``` -------------------------------- ### Get All Values Separated by IFS in Bash Source: https://speedsheet.io/s/bash?q=associative-array-only Use "${dict_1[*]}" to get values as a single word, separated by the first character of IFS. ```bash ="${dict_1[*]}" ``` -------------------------------- ### List All Processes Source: https://speedsheet.io/s/bash?q=processes-only Use the `ps` command to display information about running processes. Options like `-e` (every process) and `-f` (full format) provide detailed output. ```bash ps ``` ```bash ps -ef ``` ```bash ps -o ruser,pid,vsz,s,uid,comm -p id ``` ```bash ps -e -o ruser,pid,s,vsz,stime,time,comm ``` -------------------------------- ### Get All Keys Separated by IFS in Bash Source: https://speedsheet.io/s/bash?q=associative-array-only Use "${!dict_1[*]}" to get keys as a single word, separated by the first character of IFS. ```bash ="${!dict_1[*]}" ``` -------------------------------- ### Run Command or Fallback Source: https://speedsheet.io/s/bash Use '&&' for success and '||' for fallback to execute a command, and if it fails, execute an alternative. ```bash command_1 && successful_command || fallback_command ``` -------------------------------- ### Get Drive Size and Free Space Source: https://speedsheet.io/s/bash Displays disk usage information for specified drive paths, showing size and available space in a human-readable format. ```bash df -h drive_path ``` ```bash df -k drive_path ``` ```bash df -g drive_path ``` -------------------------------- ### Get Current User Source: https://speedsheet.io/s/bash Displays the username of the currently logged-in user. ```bash =$USER ``` ```bash logname ``` -------------------------------- ### 'Hello World' Script with User Input Source: https://speedsheet.io/s/bash This Bash script prompts the user for their name and then prints a personalized greeting. It uses `read -p` to display a prompt and capture user input. ```bash #!/usr/bin/env bash read -p "Name: " name echo "Hello $name!" ``` -------------------------------- ### Get Current User Information Source: https://speedsheet.io/s/bash?q=user-only Displays comprehensive information about the current user, including their ID, name, and associated groups. ```bash id ``` -------------------------------- ### 'Hello World' Script with Argument or Input Source: https://speedsheet.io/s/bash An advanced Bash script that greets a user. It prioritizes a name provided as a command-line argument; otherwise, it prompts the user for input. This script demonstrates basic function usage in Bash. ```bash #!/usr/bin/env bash get_name() { # stores the input into the variable '`name`': read -p "Name: " name } print_hello() { local name="$@" echo "Hello $name!" } if [[ -z "$1" ]]; then get_name else name="$@" fi print_hello "$name" ``` -------------------------------- ### Get Current Process ID Source: https://speedsheet.io/s/bash Returns the process ID of the current shell. ```bash $$ ``` ```bash echo $$ ``` -------------------------------- ### Create a File from Command-line Input Source: https://speedsheet.io/s/bash?q=files-only Create a file by typing content directly into the terminal after the `cat > file_name` command, ending with Ctrl+D. ```bash cat > file_name ...content... Ctrl + D ``` -------------------------------- ### List Top Processes by CPU Usage Source: https://speedsheet.io/s/bash?q=processes-only Use `top` to view a dynamic, real-time list of processes, sorted by CPU usage by default. The output includes PID, CPU%, Memory, and command. ```bash top ``` ```bash ps -eo pid,%cpu,%mem,vsize,start,args | sort -k 2 -nr | head -25 ``` -------------------------------- ### List Top 25 Processes by Memory Size Source: https://speedsheet.io/s/bash Shows the top 25 processes sorted by memory size. Displays Process ID, CPU %, Memory, Virtual Memory Size, Start Date, and Command-line. ```bash ps -eo pid,%cpu,%mem,vsize,start,args | sort -k 4 -nr | head -25 ``` -------------------------------- ### Get Operating System Kernel Version Source: https://speedsheet.io/s/bash Retrieves the kernel version of the operating system. ```bash uname -r ``` -------------------------------- ### Get Current User ID Source: https://speedsheet.io/s/bash?q=user-only Displays the unique numerical identifier for the current user. ```bash id -u ``` -------------------------------- ### List Top 25 Processes by CPU Usage Source: https://speedsheet.io/s/bash Shows the top 25 processes sorted by CPU usage. Displays Process ID, CPU %, Memory, Virtual Memory Size, Start Date, and Command-line. ```bash ps -eo pid,%cpu,%mem,vsize,start,args | sort -k 2 -nr | head -25 ``` -------------------------------- ### List All Users on System Source: https://speedsheet.io/s/bash Displays all user accounts on the system by reading the '/etc/passwd' file. ```bash cat /etc/passwd ``` -------------------------------- ### Get the size of a Bash array Source: https://speedsheet.io/s/bash?q=array-only Returns the number of elements currently stored in an array. ```bash array_1=("one" "two" "three") echo "${#array_1[@]}" ``` -------------------------------- ### Get CPU Type Source: https://speedsheet.io/s/bash Returns the machine hardware name, indicating the CPU type. Useful for identifying specific hardware like M1 Macs. ```bash uname -m ``` ```bash if [[ $(uname -m) == 'arm64' ]]; then echo "M1 Mac" fi ``` -------------------------------- ### Get First N Lines of String Source: https://speedsheet.io/s/bash Returns the first `count` lines of a string. Specify the number of lines using the `-n` option with `head`. ```bash command | head -n count ``` -------------------------------- ### List Mounted Devices Source: https://speedsheet.io/s/bash Displays all currently mounted file systems and their mount points. ```bash mount ``` -------------------------------- ### Get the first item from a Bash array Source: https://speedsheet.io/s/bash?q=array-only Retrieves the element at index 0 from an array. ```bash array_1=("one" "two" "three") echo "${array_1[0]}" ``` -------------------------------- ### Get Total System Memory Source: https://speedsheet.io/s/bash Extracts the total system memory in kilobytes from the `/proc/meminfo` file. ```bash grep MemTotal /proc/meminfo | awk '{print $2}' ``` -------------------------------- ### Navigate to Parent Directory Source: https://speedsheet.io/s/bash?q=symbols-only The '..' symbol represents the parent directory. ```bash cd .. ``` -------------------------------- ### Get Parameter Count Source: https://speedsheet.io/s/bash?q=parameters-only Returns the total number of command-line arguments passed to the script or function. ```bash $# ``` -------------------------------- ### List Top Processes by CPU Usage Source: https://speedsheet.io/s/bash Lists the top applications by CPU usage. ```bash top ``` -------------------------------- ### Navigate to Home Directory Source: https://speedsheet.io/s/bash?q=symbols-only The '~' symbol represents the user's home directory. ```bash cd ~ ``` -------------------------------- ### Get Command/Script Name Source: https://speedsheet.io/s/bash?q=parameters-only Retrieves the name of the script or command that was executed, including any path used. ```bash $0 ``` -------------------------------- ### Get Local IP Address Source: https://speedsheet.io/s/bash Lists the server's local IP address. Multiple commands are provided as compatibility may vary across systems. ```bash hostname -I ``` ```bash ip addr show ``` ```bash sudo /sbin/ifconfig -a ``` ```bash ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*.){3}[0-9]*).*/2/p' ``` -------------------------------- ### Set Prompt to Host Name Source: https://speedsheet.io/s/bash Sets the prompt to display the full hostname of the server. ```bash PS1=\H ``` -------------------------------- ### Get an item from a Bash array by position Source: https://speedsheet.io/s/bash?q=array-only Retrieves the element at a specific zero-based index from an array. ```bash array_1=("one" "two" "three") echo "${array_1[1]}" ``` -------------------------------- ### Access Individual Parameters Source: https://speedsheet.io/s/bash?q=parameters-only References positional parameters passed to the script, starting from $1 for the first parameter. ```bash $1 $2 $3 ... ``` -------------------------------- ### Get Script Run Command Source: https://speedsheet.io/s/bash Retrieves the command used to execute the script, including the path if it was specified. ```bash =$0 ``` -------------------------------- ### Run Command or Fallback Command Source: https://speedsheet.io/s/bash?q=command-execution-only Use '&&' and '||' to execute a fallback command if the initial command fails. ```bash command_1 && successful_command || fallback_command ``` -------------------------------- ### Get String Length Source: https://speedsheet.io/s/bash Returns the length of a string using the `${#string_name}` syntax. This is a Bash parameter expansion. ```bash string_1="12345" length="${#string_1}" # Returns 5 ``` -------------------------------- ### View First N Lines of a File Source: https://speedsheet.io/s/bash?q=files-only Use `head -n` to display a specific number of lines from the beginning of a file. ```bash head -n count file_name ``` -------------------------------- ### Show Directory Sizes Source: https://speedsheet.io/s/bash?q=files-only Displays the sizes of directories. Use the -h option for human-readable output, -k for kilobytes, or -ks to list sizes for each file. The output can be sorted and piped to head for summary information. ```bash du ``` ```bash du -h directory_path ``` ```bash du -k | sort -rn | head ``` -------------------------------- ### Get the last item from a Bash array Source: https://speedsheet.io/s/bash?q=array-only Retrieves the last element from an array using negative indexing. ```bash array_1=("one" "two" "three") echo "${array_1[-1]}" ``` -------------------------------- ### Create a User Group Source: https://speedsheet.io/s/bash Adds a new user group to the system. ```bash groupadd group_name ``` -------------------------------- ### Navigate to Current Directory Source: https://speedsheet.io/s/bash?q=symbols-only The '.' symbol represents the current directory. ```bash cd . ``` -------------------------------- ### Set Terminal Backspace Key Source: https://speedsheet.io/s/bash Configures the terminal's backspace key behavior. For example, setting it to Ctrl+H. ```bash stty erase backspace_key ``` ```bash stty erase ^H ``` -------------------------------- ### Show System Uptime Source: https://speedsheet.io/s/bash Displays how long the system has been running since the last boot. ```bash uptime ``` -------------------------------- ### List Block Level Devices Source: https://speedsheet.io/s/bash Shows all storage devices recognized at the block level by the system. ```bash lsblk ``` -------------------------------- ### List All Drives and Free Space Source: https://speedsheet.io/s/bash Shows disk usage for all mounted drives, including size and available space in a human-readable format. ```bash df -h ``` ```bash df -k ``` ```bash df -g ``` -------------------------------- ### Get Full File Path Source: https://speedsheet.io/s/bash?q=files-only Use the `realpath` command to resolve a file name to its absolute, canonical path. ```bash realpath file_name ``` -------------------------------- ### Display User Home Directory Source: https://speedsheet.io/s/bash Prints the current user's home directory path. Ensure the HOME environment variable is set. ```bash echo "$HOME" ``` -------------------------------- ### Get Array Elements (Separate Words) Source: https://speedsheet.io/s/bash?q=symbols-only The '[@]' symbol returns all elements from an array or associative array as separate words. ```bash =items_1[@] ``` -------------------------------- ### Get Variable Value Source: https://speedsheet.io/s/bash?q=variables-only Retrieves the value of a variable. Use double quotes to handle values containing spaces. ```bash =$variable_1 ="$variable_1" ="${variable_1}" ``` -------------------------------- ### Get Current User Name Source: https://speedsheet.io/s/bash?q=user-only Shows the login name of the current user. Both 'whoami' and 'logname' commands achieve this. ```bash whoami ``` ```bash logname ``` -------------------------------- ### Create an Empty File Source: https://speedsheet.io/s/bash?q=files-only Create an empty file using either `echo -n "" > file_name` or the `touch file_name` command. ```bash echo -n "" > file_name ``` ```bash touch file_name ``` -------------------------------- ### Get All Values from Bash Associative Array Source: https://speedsheet.io/s/bash?q=associative-array-only Use "${dict_1[@]}" to retrieve all values from the associative array. ```bash ="${dict_1[@]}" ``` -------------------------------- ### Check if String Starts With Prefix in Bash Source: https://speedsheet.io/s/bash?q=operators-only Use the == operator with a wildcard to verify if a string begins with a specified prefix. ```bash "$string_1" == "$start"* if [[ $string_1 == "$start"* ]] ; then ... fi ``` -------------------------------- ### Create Symbolic Link Source: https://speedsheet.io/s/bash?q=files-only Creates a symbolic link to a source file or directory. The -s option allows linking across different devices. ```bash ln -s source_path link_name ``` -------------------------------- ### Access Parameters Excluding First Source: https://speedsheet.io/s/bash?q=parameters-only References all parameters starting from the second one. Parameters are individually quoted, preserving spaces. ```bash ${@:2} ``` -------------------------------- ### Compare Two Files Source: https://speedsheet.io/s/bash?q=files-only Use the `diff` command to show line-by-line differences between two files. ```bash diff file_1 file_2 ``` -------------------------------- ### Bash Case Statement - Basic Example Source: https://speedsheet.io/s/bash?q=control-only Executes a clause based on the value of a variable. 'case' is case-sensitive, and ';;' terminates each clause. ```bash command="start" case "$command": "start") echo "Starting" ;; "stop") echo "Stopping" ;; esac ``` -------------------------------- ### Connect to SFTP Server Source: https://speedsheet.io/s/bash Connects to an SFTP server. Supports connecting with a PEM file for authentication. ```bash sftp user_id@server.com ``` ```bash sftp -i server_pem_file user_id@server.com ``` -------------------------------- ### Copy a File Source: https://speedsheet.io/s/bash?q=files-only Use the `cp` command to copy a file. Options `-a` preserves attributes, and `-v` enables verbose output. ```bash cp source_file new_file ``` -------------------------------- ### Get Operating System Type from Variable Source: https://speedsheet.io/s/bash Returns the CPU type from the OSTYPE variable. Useful for OS-specific conditional logic. ```bash $OSTYPE ``` ```bash if [[ $OSTYPE == 'darwin'* ]]; then ... fi ``` -------------------------------- ### Get Public IP Address Source: https://speedsheet.io/s/bash Retrieves the public-facing IP address of the server using an external IP information service. ```bash curl -s "ipinfo.io" | grep -Eo '"ip":.*?[^\\]*,' | sed 's/^.*: "//;s/",//' ``` -------------------------------- ### Basic String Literals Source: https://speedsheet.io/s/bash Demonstrates the basic syntax for string literals in Bash, including unquoted, single-quoted, and double-quoted strings. ```bash string 'a string' "a string" ``` -------------------------------- ### Get Public Host Name Source: https://speedsheet.io/s/bash Retrieves the public host name of the server using an external IP information service. ```bash curl -s "ipinfo.io" | grep -Eo '"hostname":.*?[^\\]*,' | sed 's/^.*: "//;s/",//' ``` -------------------------------- ### Create Symbolic Link (Copy) Source: https://speedsheet.io/s/bash?q=files-only Creates a symbolic link to a source file or directory. Using the -p option preserves the link itself, rather than copying the target's content. ```bash cp -P source_link new_link ``` -------------------------------- ### List Local Network Devices Source: https://speedsheet.io/s/bash Lists all local devices connected to the network, showing their IP addresses. ```bash arp -a ``` -------------------------------- ### Get CPU Architecture Source: https://speedsheet.io/s/bash Retrieves the CPU architecture type. Useful for conditional logic based on the system's processor. ```bash uname -p ``` ```bash if [[ $(uname -p) == 'arm' ]]; then echo "Arm Based System" fi ``` -------------------------------- ### Download File with Wget Source: https://speedsheet.io/s/bash Downloads a web page or file using wget. Use '-O' to specify the output filename and '-q' for quiet mode. ```bash wget http://site.com/page ``` ```bash wget -O file_name http://site.com/page ``` -------------------------------- ### Get all elements except the last from a Bash array Source: https://speedsheet.io/s/bash?q=array-only Returns a subarray containing all elements from the beginning up to, but not including, the last element. ```bash array_1=("one" "two" "three") subarray=("${array_1[@]:0:${#array_1[@]}-1}") echo "${subarray[@]}" ``` -------------------------------- ### View File Contents Paged Source: https://speedsheet.io/s/bash?q=files-only Use the `more` command to view file content one screen at a time. Supports basic navigation keys. ```bash more file_name ``` -------------------------------- ### Get all elements from a Bash array Source: https://speedsheet.io/s/bash?q=array-only Retrieves all elements of an array, typically used when passing the array to another command or variable. ```bash array_1=("one" "two" "three") all=("${array_1[@]}") echo "${all[@]}" ``` -------------------------------- ### Set Prompt to Bash Version Source: https://speedsheet.io/s/bash Sets the prompt to display the current Bash version. ```bash PS1=\v ``` -------------------------------- ### Get All Keys from Bash Associative Array Source: https://speedsheet.io/s/bash?q=associative-array-only Use "${!dict_1[@]}" to retrieve all keys. The order of keys is not guaranteed. ```bash ="${!dict_1[@]}" ``` -------------------------------- ### List All User Groups (Linux) Source: https://speedsheet.io/s/bash Displays all user groups on the system by reading the /etc/group file. ```bash cat /etc/group ``` ```bash cut -d: -f1 /etc/group | sort ``` -------------------------------- ### Extract Substring from Start in Bash Source: https://speedsheet.io/s/bash Extracts a substring from the beginning of a string up to a specified length. This is a specific case of general substring extraction. ```bash =${string_1:0:length} ``` ```bash string_1="012345" substring=${string_1:0:2} echo "$substring" ``` -------------------------------- ### Bash Case Statement Basics Source: https://speedsheet.io/s/bash?q=case-only Demonstrates the basic structure of a Bash case statement with multiple value clauses. ```bash case "$string_1" in value_1) ... ;; value_2) ... ;; value_3 | value_4 | value_5) ... ;; *) # Default: ... ;; esac ``` -------------------------------- ### Single-Line Comment in Bash Source: https://speedsheet.io/s/bash?q=fundamentals-only Use the hash symbol '#' to start a comment line in Bash. Any text following '#' on the same line is ignored by the interpreter. ```bash # Comments - Single Line ``` -------------------------------- ### Find Processes with Full Command-line Source: https://speedsheet.io/s/bash?q=processes-only Display the full command-line of matching processes using pgrep. This is useful when the process name alone is insufficient. ```bash pgrep -fl ... ``` ```bash pgrep -a ... ``` -------------------------------- ### Change File Permissions Only Source: https://speedsheet.io/s/bash?q=files-only Use `find` with `chmod` to selectively change permissions for files. This example sets file permissions to 644. ```bash find path -type f -exec chmod 644 {} + ``` ```bash chmod 644 $(find path -type f) ``` -------------------------------- ### Change Directory Permissions Only Source: https://speedsheet.io/s/bash?q=files-only Use `find` with `chmod` to selectively change permissions for directories. This example sets directory permissions to 755. ```bash find path -type d -exec chmod 755 {} + ``` ```bash chmod 755 $(find path -type d) ``` -------------------------------- ### Set Prompt to Host Name Up To '.' Source: https://speedsheet.io/s/bash Sets the prompt to display the hostname truncated at the first period ('.'). ```bash PS1=\h ``` -------------------------------- ### Create a New User Source: https://speedsheet.io/s/bash?q=user-only Creates a new user account. Use the -g option to add the user to a specific group. ```bash adduser user_name ``` ```bash adduser -g group_name user_name ``` -------------------------------- ### Get All Values from Associative Array Source: https://speedsheet.io/s/bash Retrieve all values from an associative array using the `array[@]` syntax. Each value is treated as a separate element. ```bash echo "${dict_1[@]}" ``` -------------------------------- ### Trace Route to Server Source: https://speedsheet.io/s/bash Traces the route to a server, mapping each hop along the way and displaying the journey time. ```bash traceroute ip_address ``` ```bash traceroute url ``` -------------------------------- ### List All Drives Source: https://speedsheet.io/s/bash Displays a list of all drives connected to the system. Note: Functionality may vary across Linux versions. ```bash diskutil list ``` -------------------------------- ### Extract Directory from File Path Source: https://speedsheet.io/s/bash?q=files-only Use `dirname` to get the directory component of a given file path. Returns '.' if no directory is present. ```bash dirname $file_path ``` ```bash directory="$(dirname "$file_path")" ``` -------------------------------- ### Switch to Root User Source: https://speedsheet.io/s/bash Switches the current user identity to the root user. Use 'su' without any options to become root. ```bash su ``` -------------------------------- ### Get Return Code Source: https://speedsheet.io/s/bash?q=parameters-only Retrieves the exit status of the last executed command or script. A value of 0 typically indicates success. ```bash $? ``` -------------------------------- ### Show Current Directory Path Source: https://speedsheet.io/s/bash?q=files-only Prints the full path of the current working directory. ```bash pwd ``` -------------------------------- ### Get Specific Value from Bash Associative Array Source: https://speedsheet.io/s/bash?q=associative-array-only Access a value by its key using the syntax "${dict_1[name]}". ```bash ="${dict_1[name]}" ``` -------------------------------- ### View File Contents Source: https://speedsheet.io/s/bash?q=files-only Use the `cat` command to display the entire content of a file to standard output. ```bash cat file_name ``` -------------------------------- ### Extract Substring from End in Bash Source: https://speedsheet.io/s/bash Extracts the remainder of a string starting from a specified position. A negative length with a preceding space extracts from the end. ```bash =${string_1:start} ``` ```bash =${string_1: -length} ``` ```bash string_1="012345" substring=${string_1:2} echo "$substring" ``` -------------------------------- ### Show Current Date Source: https://speedsheet.io/s/bash Displays the current system date and time in a default format. ```bash date ``` -------------------------------- ### Identifier Regex Pattern Source: https://speedsheet.io/s/bash?q=fundamentals-only This regex defines the valid format for Bash identifiers: starting with a letter or underscore, followed by letters, digits, or underscores. ```regex [_a-zA-Z][_0-9a-zA-Z]* ``` -------------------------------- ### List Top Processes by Memory Usage Source: https://speedsheet.io/s/bash Lists the top applications by memory usage. ```bash top -a ``` -------------------------------- ### List Open Ports Source: https://speedsheet.io/s/bash Lists all open ports on the computer that are listening for connections. ```bash netstat -tupln ``` ```bash netstat -an | grep "LISTEN" ``` -------------------------------- ### Set IFS Delimiter Source: https://speedsheet.io/s/bash Changes the Internal Field Separator (IFS) delimiter characters. This example demonstrates setting IFS to a comma and then restoring it. ```bash IFS = 'new_characters' IFS="\n" old_ifs="$IFS" IFS="," echo "${dict_1[*]}" IFS="$old_ifs" ``` -------------------------------- ### Get Current User Name via Environment Variable Source: https://speedsheet.io/s/bash?q=user-only Retrieves the current user's name by accessing the USER environment variable. ```bash echo "$USER" ``` -------------------------------- ### Set Prompt to Date Source: https://speedsheet.io/s/bash Sets the prompt to display the current date in the format 'Mon Jan 01'. ```bash PS1=\d ``` -------------------------------- ### Set Prompt to Full Current Path Source: https://speedsheet.io/s/bash Sets the prompt to display the complete, absolute path of the current working directory. ```bash PS1=\w ``` -------------------------------- ### String to SHA256 Hash using sha256sum Source: https://speedsheet.io/s/bash Converts a string to its SHA256 hash using the sha256sum command-line utility. Requires sha256sum to be installed. ```bash echo "$string_1" | sha256sum ``` -------------------------------- ### String to SHA256 Hash using OpenSSL Source: https://speedsheet.io/s/bash Converts a string to its SHA256 hash using the OpenSSL command-line tool. Requires OpenSSL to be installed. ```bash echo "$string_1" | openssl dgst -sha256 ``` -------------------------------- ### Connect to a Server via SSH Source: https://speedsheet.io/s/bash Establishes a secure terminal connection to a remote server. Use the -i option to specify an identity file for authentication. ```bash ssh user_id@server_url ``` ```bash ssh -i server_pem_file user_id@server_url ``` -------------------------------- ### Set Exit Code to True and Check Source: https://speedsheet.io/s/bash?q=boolean-only Sets the exit code to 0 using `true` and then demonstrates checking it with `echo "$?"`. ```bash true echo "$?" ``` -------------------------------- ### Extract Lines N to M from String Source: https://speedsheet.io/s/bash Returns a range of lines from a string using `sed -n 'n,mp'`. Line numbers start at 1. ```bash command | sed -n 'n,mp' ``` -------------------------------- ### List Top Processes by Memory Usage Source: https://speedsheet.io/s/bash?q=processes-only Use `top -a` to view processes sorted by memory usage. Alternatively, `ps` with specific sorting can achieve the same result. ```bash top -a ``` ```bash ps -eo pid,%cpu,%mem,vsize,start,args | sort -k 4 -nr | head -25 ``` -------------------------------- ### Get Last N Lines of String Source: https://speedsheet.io/s/bash Returns the last `count` lines of a string. Specify the number of lines using the `-n` option with `tail`. ```bash command | tail -n count ``` -------------------------------- ### Get Last 10 Lines of String Source: https://speedsheet.io/s/bash Returns the last 10 lines of a string using the `tail` command. Pipe the string output to `tail`. ```bash command | tail ``` -------------------------------- ### Display Primary Prompt String Source: https://speedsheet.io/s/bash Outputs the string used for the primary command prompt. ```bash $PS1 ``` -------------------------------- ### Create a File from Script using Stream Literals Source: https://speedsheet.io/s/bash?q=files-only Use stream literals (e.g., `<< END_LABEL`) within a script to create a file with multi-line content. ```bash cat > file_name << END_LABEL ...content... ...content... ...content... END_LABEL ``` -------------------------------- ### Set Prompt to Time (HH:MM AM/PM) Source: https://speedsheet.io/s/bash Sets the prompt to display the current time in 12-hour format with AM/PM indicator. ```bash PS1=\@ ``` -------------------------------- ### Show Symbolic Link Target Source: https://speedsheet.io/s/bash?q=files-only Displays the target file or directory that a symbolic link points to. ```bash ls -l link_name ``` -------------------------------- ### View Memory Allocation By Type Source: https://speedsheet.io/s/bash Displays detailed memory information, including allocation for different memory types on the system. ```bash cat /proc/meminfo ``` -------------------------------- ### Multiline Statement Example Source: https://speedsheet.io/s/bash?q=fundamentals-only Use a backslash '\' at the end of a line to indicate that the statement continues on the next line. This improves readability for long commands or strings. ```bash echo "Part 1 and " \ "part 2 and " \ "part 3." ``` -------------------------------- ### Display Host Name Source: https://speedsheet.io/s/bash Outputs the hostname of the computer the script is running on. ```bash $HOSTNAME ``` -------------------------------- ### Run Multiple Commands Sequentially Source: https://speedsheet.io/s/bash?q=command-execution-only Use ';' to separate and execute multiple commands in a single line. ```bash echo "Hello"; echo "There" ``` -------------------------------- ### Extract File Name Without Extension or Directory Source: https://speedsheet.io/s/bash?q=files-only Combine `basename` and parameter expansion `${file_name%.*}` to get the base file name without extension or path. ```bash base_name="$(basename "${file_name%.*}")" ```