### Bashrc Configuration Source: https://context7.com/bahamas10/bash-course/llms.txt Provides an example of a ~/.bashrc file, demonstrating how to configure the interactive shell environment with environment variables, aliases, shell options, and custom functions like a color display utility. ```bash #!/usr/bin/env bash # ~/.bashrc # Only run for interactive shells [[ -n $PS1 ]] || return # Environment variables export EDITOR='vim' export PAGER='less' # Shell options shopt -s cdspell # correct minor cd typos shopt -s checkwinsize # update LINES/COLUMNS after commands shopt -s extglob # extended globbing patterns # Useful aliases alias ll='ls -lha' alias ..='cd ..' # Enable color for ls if ls --color=auto /dev/null &>/dev/null; then alias ls='ls -p --color=auto' else alias ls='ls -p -G' fi # Custom function colors() { local i for i in {0..255}; do printf "\x1b[38;5;${i}mcolor %d\n" "$i" done tput sgr0 } ``` -------------------------------- ### Search man pages for 'dave' and 'file' with grep Source: https://github.com/bahamas10/bash-course/blob/main/notes/05-01-sed-awk-grep/readme.md These examples show how to use grep to search the man page for 'ls' for specific keywords like 'dave' and 'file'. They also demonstrate piping the output to 'wc' to count lines, words, or characters, illustrating basic man page exploration and text analysis. ```bash man ls | grep dave ``` ```bash man ls | grep file ``` ```bash man ls | grep file | wc -w ``` ```bash man ls | grep file | wc -l ``` ```bash man ls | grep file | wc ``` -------------------------------- ### List Files with Partial Name Matches using Bash Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-00-basic-globbing/readme.md Shows how to use globbing to list files based on partial name matches. 'foo.*' matches any file starting with 'foo.' and followed by any characters, while 'bar.*' does the same for 'bar.'. ```bash ls -1 files/foo.* ``` ```bash ls -1 files/bar.* ``` -------------------------------- ### Bash Command Execution in Conditional Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-03-conditionals/readme.md Demonstrates using a simple command like 'true' within an 'if' statement to control script execution. This is a basic example of conditional command execution. ```bash if true; then echo hi fi ``` -------------------------------- ### Basic Bash Commands and TTY Check Examples Source: https://github.com/bahamas10/bash-course/blob/main/notes/14-02-isatty/readme.md This section shows basic bash commands like 'ls' and 'ls | wc -l'. It also demonstrates the output of the TTY check script when its output is piped to 'cat', illustrating how piping affects the TTY status. ```bash ls ls | wc -l ``` ```bash ./check-terminal ./check-terminal | cat ``` -------------------------------- ### Process text with sed, awk, and grep Source: https://context7.com/bahamas10/bash-course/llms.txt Examples of using standard Unix text processing tools for data extraction, transformation, and counting. ```bash #!/usr/bin/env bash cat /etc/passwd | grep nobody | cut -d : -f 7 | sed 's|/usr/bin/|/tmp/sbin/|' cat /etc/passwd | awk -F : '/^[^#]/ { printf("the shell is %s\n", $7); }' ``` -------------------------------- ### Nested Brace Expansion for Path Generation Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-00-brace-string-expansion/readme.md Utilizes nested brace expansion to generate complex directory and file paths. The example demonstrates creating a list of files across multiple directories and counting the resulting array size. ```bash array=(/etc/{foo,bar,baz}/{1,2,3}.txt) echo "${#array[@]} items" for item in "${array[@]}"; do echo "$item" done ``` -------------------------------- ### Set Foreground Colors in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/14-00-color/readme.md Shows how to change text color using ANSI escape codes and tput setaf. It includes a loop example to iterate through 256 available terminal colors. ```bash tput setaf 1; echo hi tput setaf 2; echo hi echo -e '\e[31mhi' printf '\e[38;5;128mHello\n' colors () { local i for i in {0..255}; do printf '\e[38;5;%dmcolor %d\n' "$i" "$i"; done printf '\e[0m' } ``` -------------------------------- ### Apply Bold Text Formatting in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/14-00-color/readme.md Demonstrates multiple ways to apply bold formatting to terminal output using ANSI escape sequences and the tput utility. It includes examples using echo, printf, and tput to toggle styles. ```bash echo -e '\e[1mhello' echo $'\e[1mhello' echo $'\033[1mhello' echo $'\x1b[1mhello' tput bold; echo hi; tput sgr0 echo -e '\e[1mhello\e[0m' ``` -------------------------------- ### Bash Date Formatting with 'printf' command Source: https://github.com/bahamas10/bash-course/blob/main/notes/11-01-date-formatting/readme.md This snippet illustrates date and time formatting using the 'printf' command, which offers more control and flexibility, especially when dealing with epoch timestamps or specific time representations. It includes examples of formatting epoch seconds and real-time values. ```bash printf "%($datefmt)T\n" -1 printf '%T\n' printf '%()T\n' printf '%(%H:%M:%S)T\n' -1 printf '%(%H:%M:%S)T\n' -2 printf '%(%H:%M:%S)T\n' 0 printf '%(%H:%M:%S)T\n' 5000 ``` -------------------------------- ### Bash Conditional: File Existence Check Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-03-conditionals/readme.md Shows how to use the 'if' statement to check if a specific file exists in the file system. The example checks for the presence of '/etc/passwd'. ```bash if [[ -f /etc/passwd ]]; then echo /etc/passwd is a file fi ``` -------------------------------- ### Bash: Process substitution with while loop Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-06-process-substitution/readme.md This example utilizes Bash's process substitution ('< <(...)') to feed the output of 'grep' into a 'while read' loop. It counts the lines processed. Dependencies: grep, Bash shell. ```bash i=0 while read -r word; do echo "$word" ((i++)) done < <(grep d /usr/share/dict/words) echo "found $i words" ``` -------------------------------- ### Bash: Process output with a while loop and here-string Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-06-process-substitution/readme.md This example captures 'grep' output into a variable and processes it line by line using a 'while read' loop with a here-string ('<<<'). It counts the processed lines. Dependencies: grep, Bash shell. ```bash words=$(grep d /usr/share/dict/words) i=0 while read -r word; do echo "$word" ((i++)) done <<< "$words" echo "found $i words" ``` -------------------------------- ### List Files with Character Set Matching using Bash Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-00-basic-globbing/readme.md Demonstrates using character sets within globbing patterns. 'ba[rz].txt' will match files that start with 'ba', followed by either 'r' or 'z', and end with '.txt', such as 'bar.txt' or 'baz.txt'. ```bash ls -1 files/ba[rz].txt ``` -------------------------------- ### Bash: Indexed Arrays for Ordered Collections Source: https://context7.com/bahamas10/bash-course/llms.txt Shows how to declare and manipulate indexed arrays in Bash. Covers accessing elements by index (including negative indexing), iterating over arrays, slicing, appending, and getting array length. ```bash #!/usr/bin/env bash # Array declaration array=(foo bar baz 'hello world') # Access elements echo "${array[0]}" # foo echo "${array[-1]}" # hello world # Iterate over array for item in "${array[@]}"; do echo "item is: $item" done # Array operations newarray=("${array[@]:1}") # slice from index 1 array+=("new item") # append element echo "${#array[@]}" # array length ``` -------------------------------- ### Replace Shell Path with sed Source: https://github.com/bahamas10/bash-course/blob/main/notes/05-01-sed-awk-grep/readme.md This command uses sed to replace the '/usr/bin/' path with '/tmp/sbin/' in the 7th field (shell path) of lines from /etc/passwd that do not start with '#'. It demonstrates basic string replacement. ```bash cat /etc/passwd | grep nobody | cut -d : -f 7 | sed 's|/usr/bin/|/tmp/sbin/|' ``` -------------------------------- ### Bash Loop: Infinite Loop with 'ls' Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-03-conditionals/readme.md An example of a potentially infinite 'while' loop that executes as long as the 'ls' command returns a successful exit status. It includes a 'sleep' command to pause execution. ```bash while ls; do sleep 1 fi ``` -------------------------------- ### Extract Shell Information with awk Source: https://github.com/bahamas10/bash-course/blob/main/notes/05-01-sed-awk-grep/readme.md This command uses awk to process the /etc/passwd file. It filters lines that do not start with '#' and then prints the 7th field, which represents the user's shell. This showcases awk's pattern matching and field extraction capabilities. ```bash cat /etc/passwd | awk -F : '/^[^#]/ { printf("the shell is %s\n", $7); }') ``` -------------------------------- ### Bash globstar Option for Recursive Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-02-glob-options/readme.md Explains the 'globstar' shell option in Bash, enabling the '**' pattern for recursive directory matching. This allows matching files in subdirectories. The example shows its usage with 'find', 'echo', and array assignments, and how it interacts with 'dotglob' to include hidden files and directories. ```bash cd ~/dev/ysap find . echo ** shopt -s globstar echo ** printf '%s ' ** shopt -s dotglob txt=( ./**/*.txt ) count it, show loop ``` -------------------------------- ### Searching Files and Directories with find Source: https://github.com/bahamas10/bash-course/blob/main/notes/05-02-find-cmd/readme.md Demonstrates basic usage of the find command to list files and directories. Includes filtering by type and counting results using pipes. ```bash find . find /var/empty find /var/empty -type f find /usr/share -type f | wc -l find /usr/share -type d | wc -l find /usr/share -type l | wc -l ``` -------------------------------- ### Format output with printf Source: https://context7.com/bahamas10/bash-course/llms.txt Shows how to use printf for precise control over output formatting, including padding and alignment. ```bash #!/usr/bin/env bash printf '%5s %5s\n' hello world printf '%-5s %-5s\n' a b printf '%05d\n' 55 ``` -------------------------------- ### Use process substitution for file-like input Source: https://context7.com/bahamas10/bash-course/llms.txt Shows how to use the <(command) syntax to treat command output as a file, avoiding subshell issues. ```bash #!/usr/bin/env bash i=0 while read -r word; do echo "$word" ((i++)) done < <(grep d /usr/share/dict/words) echo "found $i words" ``` -------------------------------- ### Bash: Basic Script Writing and I/O Source: https://context7.com/bahamas10/bash-course/llms.txt Demonstrates fundamental Bash scripting techniques including variable assignment, reading user input, accepting command-line arguments, and basic output. It covers the shebang line and variable expansion. ```bash #!/usr/bin/env bash # Basic variable assignment and output name='dave' items=5 echo "user $name has $items items" # Reading input from the user read -p 'enter your name: ' name echo "hello $name" # Accepting command-line arguments name=$1 echo "hello $name" # Combining both approaches with fallback if [[ -n $1 ]]; then name=$1 else read -p 'enter your name: ' name fi echo "hello $name" ``` -------------------------------- ### Bash: Basic Command Output and Return Code Source: https://github.com/bahamas10/bash-course/blob/main/notes/07-02-return-vs-output/readme.md Demonstrates how to execute a simple command, display its standard output, and then check its return code using the '$?' variable. This illustrates the fundamental concept of command execution and its exit status. ```bash uname echo $? ``` -------------------------------- ### Navigate and Manage Directories via Shell Source: https://github.com/bahamas10/bash-course/blob/main/notes/01-00-terminal-and-finder/readme.md Demonstrates how to change directories, create a new folder, and open it in the graphical file manager. This sequence highlights the interaction between the shell and the OS file system. ```bash cd ~/Desktop mkdir foo open foo ``` -------------------------------- ### Basic String Formatting with printf Source: https://github.com/bahamas10/bash-course/blob/main/notes/11-00-printf/readme.md Demonstrates the correct usage of printf for printing strings compared to echo. It shows how to use format specifiers to control layout and padding. ```bash s='hello world' printf '%s\n' "$s" printf '>>> the string is: %s!! <<' "$s" printf '%5s %5s\n' hello world printf '%-5s %-5s\n' a b printf '>>%*s<<\n' 20 dave ``` -------------------------------- ### Basic Hello World Script Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-00-actually-scripting/readme.md A simple script that outputs the string 'hello' to the standard output. It demonstrates the fundamental use of the echo command. ```bash echo hello ``` -------------------------------- ### Generating Number Sequences with `seq` Command in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-02-braces-numeric/readme.md Illustrates how to use the `seq` command to generate sequences of numbers, including step values. ```bash seq 1 10 seq 1 20 seq 5 seq 1 5 20 # wrong seq 1 20 5 # wrong ``` -------------------------------- ### Basic and Variable-based Brace Expansion Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-00-brace-string-expansion/readme.md Demonstrates how to use curly braces to generate multiple strings from a single command. It also shows how to combine brace expansion with shell variables to create dynamic file naming patterns. ```bash echo {hello,world} echo "{hello,world}" echo my-file.{txt,jpg,mov} filename='my-file' echo "$filename."{txt,jpg,mov} ``` -------------------------------- ### File Manipulation with Brace Expansion and Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-01-braces-and-globbing/readme.md Demonstrates creating multiple files using brace expansion and listing them using globbing patterns. It also highlights the difference between standard globbing and extended globbing when files do not exist. ```bash mkdir files echo files/{foo,bar,baz}.{jpg,txt} touch files/{foo,bar,baz}.{jpg,txt} printf '<%s>\n' files/*.txt # explain that it doesn't have to exist - compare to ext glob printf '<%s>\n' files/{foo,bar}.txt printf '<%s>\n' files/@(foo|bar).txt ls files/*.{txt,jpg} mkdir empty ls empty/*.{txt,jpg} printf '<%s>\n' empty/*.{txt,jpg} ``` -------------------------------- ### Bash: Functions for Reusable Code Source: https://context7.com/bahamas10/bash-course/llms.txt Illustrates how to define and use functions in Bash for encapsulating reusable code blocks. It shows how to pass arguments, use local variables, and check function return codes. ```bash #!/usr/bin/env bash greet() { local name=$1 echo "hello $name (from func)" return 5 } # Call function with arguments for name in "$@"; do greet "$name" done # Check return code greet dave echo $? # Output: 5 ``` -------------------------------- ### Advanced Filtering and Execution with find Source: https://github.com/bahamas10/bash-course/blob/main/notes/05-02-find-cmd/readme.md Shows how to use name-based filtering with case-insensitive options and how to execute commands on found files using the -exec flag. ```bash find /usr/share/ -type f -name '*.plist' -iname 'info*' find /usr/share/ -type f -name 'Info.plist' -exec echo the file is {} \; ``` -------------------------------- ### Generate strings with brace expansion Source: https://context7.com/bahamas10/bash-course/llms.txt Demonstrates generating multiple strings or paths using brace expansion for efficient command construction. ```bash #!/usr/bin/env bash echo my-file.{txt,jpg,mov} array=(/etc/{foo,bar,baz}/{1,2,3}.txt) ``` -------------------------------- ### Basic Numeric Brace Expansion in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-02-braces-numeric/readme.md Demonstrates the fundamental usage of numeric brace expansion for creating simple number sequences. ```bash echo {1,2} echo {1..2} echo {1..20} echo {5..10} echo {1..100..5} ``` -------------------------------- ### Match files with globbing Source: https://context7.com/bahamas10/bash-course/llms.txt Shows how to use glob patterns to match filenames and populate arrays. ```bash #!/usr/bin/env bash files=(files/*.txt) for f in "${files[@]}"; do echo "file: $f" done ``` -------------------------------- ### Bash Epoch Timestamp Formatting Source: https://github.com/bahamas10/bash-course/blob/main/notes/11-01-date-formatting/readme.md This snippet demonstrates how to get and format the current date and time as an epoch timestamp (seconds since the Unix epoch) in Bash. It shows direct output using 'date +%s' and formatted output using 'printf', as well as accessing built-in variables like EPOCHSECONDS and EPOCHREALTIME. ```bash date +%s printf '%(%s)T\n' -1 printf -v var '%(%s)T\n' -1 echo $EPOCHSECONDS echo $EPOCHREALTIME ``` -------------------------------- ### Defining and Calling Bash Functions Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-02-functions/readme.md Shows how to define a function and call it with various argument configurations, including passing individual arguments and all positional parameters. ```bash my-func() { echo hello from my function echo arg1 is $1 } my-func my-func hello! my-func $1 $2 $3 my-func "$@" ``` -------------------------------- ### Perform string manipulation with parameter expansion Source: https://context7.com/bahamas10/bash-course/llms.txt Illustrates case conversion, setting default values, pattern replacement, and substring extraction using native Bash parameter expansion. ```bash #!/usr/bin/env bash # Case conversion s='dave eddy' echo "${s^}" # Dave eddy echo "${s^^}" # DAVE EDDY echo "${s,,}" # dave eddy # Default values name=${1:-dave} # Pattern replacement path=/home/dave/abc.txt echo "${path/a/o}" echo "${path##*/}" # Substring extraction echo "${s:0:4}" ``` -------------------------------- ### Basic Variable Assignment and Command Substitution Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-04-command-substitution/readme.md Demonstrates assigning static values and command outputs to variables. Shows the transition from legacy backtick syntax to the preferred $(...) syntax. ```bash thing='whatever' echo "thing is $thing" thing=$(whoami) thing=$(ls) ``` -------------------------------- ### Bash dotglob Option for Hidden Files Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-02-glob-options/readme.md Illustrates the 'dotglob' shell option in Bash, which controls whether globbing patterns match files starting with a dot (hidden files). When enabled, patterns like '*' will include hidden files. When disabled, they are excluded by default. This impacts commands like 'ls', 'echo', and array assignments. ```bash touch empty/.hidden-file ls empty ls -a empty echo empty/* shopt -s dotglob echo empty/* arr=(empty/*) echo "${arr[*]}" shopt -u dotglob arr=(empty/* empty/.*) echo "${arr[*]}" shopt -s dotglob echo empty/* empty/.* ``` -------------------------------- ### Bash: Command Substitution for Capturing Output Source: https://context7.com/bahamas10/bash-course/llms.txt Illustrates command substitution in Bash using `$(command)` syntax to capture the output of commands into variables. Shows basic usage and nested substitution. ```bash #!/usr/bin/env bash # Capture command output current_user=$(whoami) echo "current user is $current_user" # Nested substitution echo "$(echo "$(whoami)")" ``` -------------------------------- ### Accessing and Formatting Environment Variables Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-02-more-variables/readme.md Demonstrates how to display common system environment variables. It also shows how to pipe the PATH variable into the tr command to display each directory on a new line. ```bash echo $PATH echo $PATH | tr ':' '\n' echo $PWD echo $USER echo $SHELL echo $HOSTNAME ``` -------------------------------- ### Calculate Process Limit Source: https://github.com/bahamas10/bash-course/blob/main/notes/17-00-forkbomb/readme.md These commands use the 'bc' arbitrary precision calculator to compute powers of 2. '2^5' and '2^6' are calculated, which might be used to estimate or demonstrate the exponential growth of processes in a forkbomb scenario. ```shell bc 2^5 2^6 ``` -------------------------------- ### File Creation and Redirection in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/01-03-searching-in-files/readme.md Demonstrates how to create files using touch and manage content using standard output redirection. The '>' operator overwrites a file, while '>>' appends content to an existing file. ```bash touch file.txt echo "hello" > file.txt echo "a" >> file.txt echo "b" >> file.txt echo "c" >> file.txt ``` -------------------------------- ### Input Redirection Techniques Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-05-io/readme.md Illustrates equivalent methods for passing file contents into a script using pipes and input redirection operators. ```bash cat /usr/share/dict/words | ./script < /usr/share/dict/words ./script ./script < /usr/share/dict/words ``` -------------------------------- ### Declare and Initialize Associative Arrays in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-02-associative-arrays/readme.md Demonstrates how to declare an associative array, assign values to specific keys, and retrieve values. It also shows how to iterate over keys and values using expansion syntax. ```bash declare -A array=() array[foo]=1 array[bar]=2 array[baz]=3 echo "${array[foo]}" echo "${array[bar]}" for key in "${!array[@]}"; do value=${array[$key]} echo "$key is $value" done ``` -------------------------------- ### Search files with find Source: https://context7.com/bahamas10/bash-course/llms.txt Demonstrates searching directory trees based on criteria and executing commands on the results. ```bash #!/usr/bin/env bash find /usr/share/ -type f -name '*.plist' -iname 'info*' find /usr/share -type f -name 'Info.plist' -exec echo "the file is {}" \; ``` -------------------------------- ### Iterating with `seq` and Brace Expansion in Bash `for` Loops Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-02-braces-numeric/readme.md Shows how to use `seq` command and brace expansion within `for` loops to iterate over number sequences. ```bash for i in $(seq 1 10); do echo "$i" done for i in {1..10}; do echo "$i" done ``` -------------------------------- ### Bash `for` Loops with Variables and `seq` Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-02-braces-numeric/readme.md Shows how to use variables to define the range and step for number sequences in `for` loops, using both brace expansion and the `seq` command. ```bash max=4 for i in {1..$max}; do echo "$i" done max=4 for i in $(seq 1 "$max"); do echo "$i" done ``` -------------------------------- ### Create and Use Named Pipes Source: https://github.com/bahamas10/bash-course/blob/main/notes/13-01-named-pipes/readme.md Demonstrates the basic workflow of creating a named pipe and using it to pass data between two processes. One process reads from the pipe while the other writes to it, effectively blocking until the other end is opened. ```bash mkfifo pipe # Terminal A cat pipe # Terminal B echo "hi" > pipe ``` -------------------------------- ### Defining and Invoking Bash Functions Source: https://github.com/bahamas10/bash-course/blob/main/notes/07-00-sourcing/readme.md Demonstrates the basic syntax for defining a function in Bash and calling it with arguments. This approach is useful for modularizing repetitive tasks within a script. ```bash greet() { echo "Hello, $1" } greet dave greet john ``` -------------------------------- ### Iterating and Executing Commands in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-02-functions/readme.md Demonstrates a simple loop that iterates over a list of names and executes an external script or command for each item. ```bash for name in foo bar baz; do ./greet "$name" done ``` -------------------------------- ### Basic Bash Scripting with Variables Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-03-vim-crash-course/readme.md Demonstrates how to create a simple Bash script that outputs the current user and the current date. This script uses standard shell variable assignment and command substitution. ```bash #!/bin/bash echo "hello $USER" now=$(date) echo "Current date and time: $now" ``` -------------------------------- ### Capturing Command Output Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-02-more-variables/readme.md Illustrates how to store the output of a command into a variable using both legacy backtick syntax and modern command substitution syntax. ```bash thing=`uname` thing=$(uname) echo $thing ``` -------------------------------- ### Bash String Replacement with Parameter Expansion Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-00-parameter-expansion/readme.md Shows how to perform string replacements in bash using parameter expansion. This includes replacing the first occurrence, all occurrences, and pattern-based replacements. ```bash path=/home/dave/abc.txt echo "$path" | tr a o echo "${path/a/o}" echo "${path//a/o}" basename "$path" dirname "$path" echo "${path}" echo "${path#*/}" echo "${path##*/}" echo "${path}" echo "${path%/*}" ``` ```bash echo "${path//[abc]/5}" ``` -------------------------------- ### Execute Bash Scripts with Debugging Flags Source: https://github.com/bahamas10/bash-course/blob/main/notes/06-00-bash-arguments/readme.md Demonstrates how to run Bash scripts with the -x flag to trace execution. It also shows how to customize the debug prompt using the PS4 environment variable. ```bash bash -x ./00-simple-script PS4='>>>>' bash -x 00-simple-script ``` -------------------------------- ### Read input line by line Source: https://context7.com/bahamas10/bash-course/llms.txt Demonstrates the read builtin for processing input streams line by line, using -r to prevent backslash interpretation. ```bash #!/usr/bin/env bash while read -r line; do echo "we read line: $line" done ``` -------------------------------- ### Process Input Streams with While Loops Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-05-io/readme.md Shows how to iterate over lines of input provided via a pipe or redirection using a while loop and the read command. ```bash while read -r line; do echo "got line: $line" done ``` -------------------------------- ### Handling Arguments in Bash Aliases and Functions Source: https://github.com/bahamas10/bash-course/blob/main/notes/16-01-aliases-with-arguments/readme.md Demonstrates the limitation of passing arguments to aliases and shows the correct implementation using shell functions. The mkdc function combines directory creation and navigation into a single command. ```bash # Standard aliases with arguments (often ineffective) alias mkdc='mkdir $1 && cd $1' alias foo='echo $1 $2' # Function implementation for argument support mkdc() { mkdir "$1" && cd "$1" } ``` -------------------------------- ### Nested Command Substitution Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-04-command-substitution/readme.md Illustrates how to nest command substitutions using the $(...) syntax. This approach avoids the complexity and escaping issues associated with nested backticks. ```bash echo "$(whoami)" echo "$(echo "$(whoami)")" echo "$(echo "$(echo "$(whoami)")")" ``` -------------------------------- ### Bash Script Sourcing Source: https://context7.com/bahamas10/bash-course/llms.txt Illustrates how to source Bash scripts to execute them in the current shell context, enabling function and variable sharing. It shows a library script and a main script that sources it. ```bash #!/usr/bin/env bash # File: lib/greetings greet() { name=$1 echo "hello $name" } goodbye() { name=$1 echo "goodbye $name" } # Only run if executed directly (not sourced) if ! (return 2>/dev/null); then greet dave goodbye john fi ``` ```bash #!/usr/bin/env bash # File: main-script # Source the library source ./lib/greetings # Now functions are available greet "world" goodbye "friend" ``` -------------------------------- ### Making a Bash Script Executable Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-04-file-permissions/readme.md This snippet demonstrates how to make a Bash script executable using the chmod command. It covers the process from creating a script to running it directly. This is essential for automating tasks in a Linux/Unix environment. ```bash chmod +x script.sh ./script.sh ``` -------------------------------- ### Bash: Associative Arrays for Key-Value Pairs Source: https://context7.com/bahamas10/bash-course/llms.txt Explains how to use associative arrays (dictionaries) in Bash, requiring `declare -A`. Demonstrates adding key-value pairs and iterating over keys and values. ```bash #!/usr/bin/env bash declare -A arr arr[foo]=1 arr[bar]=2 arr[baz]=3 # Iterate over keys and values for key in "${!arr[@]}"; do value=${arr[$key]} echo "got $key=$value" done # Output (order not guaranteed): # got bar=2 # got baz=3 # got foo=1 ``` -------------------------------- ### Chaining Commands with Pipelines Source: https://github.com/bahamas10/bash-course/blob/main/notes/01-03-searching-in-files/readme.md Shows how to combine multiple commands using the pipe operator (|) to pass the output of one command as the input to another, enabling complex text processing workflows. ```bash cat file.txt | grep -v "exclude" | grep -o "include" ``` -------------------------------- ### C-style `for` Loop in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-02-braces-numeric/readme.md Demonstrates the C-style `for` loop syntax in Bash for iterating through a numerical range. ```bash max=4 for ((i = 1; i <= max; i++)); do echo "$i" done ``` -------------------------------- ### Calculate String Length and Handle ANSI Sequences in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/16-02-ansi-length/readme.md Demonstrates the correct way to interpret ANSI escape codes using the $'' syntax instead of $"". It also shows how to calculate string length using shell parameter expansion and the wc utility for byte counting. ```bash # Correct ANSI escape usage echo $'\e[33mHello World\e[0m' # Calculate string length s="Hello World" echo "${#s}" # Byte counting with wc echo -n 'Hello World' | wc -c ``` -------------------------------- ### Sourcing External Bash Libraries Source: https://github.com/bahamas10/bash-course/blob/main/notes/07-00-sourcing/readme.md Shows how to include functions from external files into the current shell environment. Using the source command or the dot operator allows for better code organization. ```bash source ./lib/greet # Alternatively using the dot operator . ./lib/greet ``` -------------------------------- ### Numeric Formatting and Base Conversion Source: https://github.com/bahamas10/bash-course/blob/main/notes/11-00-printf/readme.md Explains how to format integers with padding and how printf interprets different numeric bases, including octal and hexadecimal inputs. ```bash printf '%d\n' 55 printf '%5d\n' 55 printf '%05d\n' 55 printf '%d\n' 010 printf '%d\n' 0xff ``` -------------------------------- ### List Specific File Extensions with Bash Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-00-basic-globbing/readme.md Demonstrates using globbing patterns to list files with specific extensions. '*.txt' matches any file ending in '.txt', and '*.jpg' matches any file ending in '.jpg'. ```bash ls -1 files/*.txt ``` ```bash ls -1 files/*.jpg ``` -------------------------------- ### Read User Input in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-05-io/readme.md Demonstrates how to capture user input from the terminal using the read command and display it back using echo. ```bash read -r foo echo "you said: $foo" ``` -------------------------------- ### Iterating with For Loops Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-00-actually-scripting/readme.md Demonstrates the syntax for a basic for-loop in Bash to iterate over a space-separated list of items. It executes a block of code for each item in the sequence. ```bash for thing in foo bar baz bat; do echo "thing is $thing" done ``` -------------------------------- ### Basic File Manipulation Commands Source: https://github.com/bahamas10/bash-course/blob/main/notes/01-00-terminal-and-finder/readme.md Covers standard file operations including creation, editing, content display, redirection, and deletion. These commands form the basis of file system interaction in Unix environments. ```bash touch file.txt vim file.txt cat file.txt echo "hi" > file.txt rm file.txt ``` -------------------------------- ### Bash: For Loops for Iteration Source: https://context7.com/bahamas10/bash-course/llms.txt Explains various ways to use for loops in Bash, including iterating over lists of words, character ranges, numeric ranges, and C-style numeric loops for controlled iteration. ```bash #!/usr/bin/env bash # Iterate over a list for name in foo bar baz; do echo "name is $name" done # Character range for c in {a..f}; do echo "c is $c" done # Numeric range for i in {1..5}; do echo "i is $i" done # C-style loop with variable max=5 for ((i = 0; i < max; i++)); do echo "thing is $i" done ``` -------------------------------- ### Bash Extended Globbing Pattern Explanations Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-01-extended-globbing/readme.md Provides a reference for common extended globbing pattern syntax in Bash. These patterns offer more expressive ways to match filenames than standard globbing. ```bash +(pattern) => matches one or more occurrences of pattern ?(pattern) => matches zero or one occurrence of pattern *(pattern) => matches zero or more occurrences of pattern @(pattern) => matches exactly one occurrence of pattern (alternation) ``` -------------------------------- ### Bash Arithmetic Expansion and Operations Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-05-arithmetic-expression/readme.md Demonstrates basic arithmetic operations, variable usage in expressions, and the use of '((...))' for arithmetic and status checking. It shows how non-numeric strings result in 0 in arithmetic contexts. ```bash echo $((2 + 2)) echo $((18)) a=2 b=3 echo $(($a + $b)) echo $((a + b)) a='hello' b='goodbye' echo $((a + b)) i=0 ((i++)) echo "$i" ((i = i + 1)) ((i = 57)) ((2 + 2)) echo $? ((2 - 2)) echo $? ((a = 5, b = 7)) ``` -------------------------------- ### Define Useful Bash Aliases Source: https://github.com/bahamas10/bash-course/blob/main/notes/15-01-customize-bashrc/readme.md Sets up common aliases for system utilities like grep, file opening, and hardware monitoring. It also includes conditional logic to configure 'ls' for colorized output based on the operating system. ```bash grep --color=auto < /dev/null &>/dev/null && alias grep='grep --color=auto' xdg-open --version &>/dev/null && alias open='xdg-open' command -v system_profiler &>/dev/null && alias wattage='system_profiler SPPowerDataType | grep Wattage' if ls --color=auto &>/dev/null; then alias ls='ls -p --color=auto' else alias ls='ls -p -G' fi ``` -------------------------------- ### Bash: Case Statements for Pattern Matching Source: https://context7.com/bahamas10/bash-course/llms.txt Demonstrates the use of `case` statements in Bash for pattern matching against strings. It provides a cleaner alternative to multiple `if-elif` conditions and includes a catch-all pattern. ```bash #!/usr/bin/env bash s=$1 case "$s" in dave) echo "hi dave";; buddy) echo "ohhh there he is";; guy) echo "uh oh here comes trouble";; *) echo "idk who you are";; esac ``` -------------------------------- ### Capturing Function Output Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-04-command-substitution/readme.md Shows how to capture the standard output of a user-defined function into a variable using command substitution. ```bash my-func() { echo hi } thing=$(my-func) echo "thing is $thing" ``` -------------------------------- ### Searching Patterns with Grep Source: https://github.com/bahamas10/bash-course/blob/main/notes/01-03-searching-in-files/readme.md Explains how to search for text patterns within files. Includes flags for case-insensitivity (-i), showing context lines (-A, -B, -C), displaying only matching parts (-o), and inverting matches (-v). ```bash grep "dave" /usr/share/dict/words grep "b" file.txt grep -A1 "b" file.txt grep -i "pattern" file.txt grep -o "pattern" file.txt grep -v "pattern" file.txt ``` -------------------------------- ### Viewing File Permissions and Ownership Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-04-file-permissions/readme.md This snippet shows how to view file permissions and ownership using the stat and ls -lha commands. Understanding these outputs is crucial for diagnosing permission issues and managing file access. It helps in identifying user, group, and other read/write/execute permissions. ```bash stat script.sh stat /usr/bin/ls ls -lha . ``` -------------------------------- ### Bash String Casing Manipulation Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-00-parameter-expansion/readme.md Demonstrates bash parameter expansion for changing the case of strings. It shows how to convert to uppercase, lowercase, and specific character casing. ```bash s='dave eddy' ${s^} ${s^^} ${s^^d} ${s^d} ${s^^da} ${s^^[da]} ${s,,} s='DAVE EDDY' ${s,,} ${s,} ${s,,D} ${s,D} ${s,,DA} ${s,,[DA]} ``` -------------------------------- ### Iterating over Expanded File Lists Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-00-brace-string-expansion/readme.md Shows how to capture brace-expanded patterns into an array and iterate over them using a for loop. This is useful for batch processing files generated from a pattern. ```bash filename='my-file' array=("$filename."{txt,jpg,mov}) for item in "${array[@]}"; do echo "$item" done ``` -------------------------------- ### Enable and Use Extended Globbing in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-01-extended-globbing/readme.md This snippet demonstrates how to enable extended globbing in Bash using 'shopt -s extglob' and then applies various extended globbing patterns to list files. It covers negation, one-or-more, and alternation patterns. ```bash set -H shopt -s extglob # List all files NOT ending in .txt ls -1 files/!(*.txt) # List files ending in .txt that match either foo or bar ls -1 files/+(foo|bar).txt # List files ending in .txt that match foo or bar (alternation) ls -1 files/@(foo|bar).txt # List files ending in .txt that match foo or ba followed by any single character ls -1 files/@(foo|ba?).* ``` -------------------------------- ### Viewing File Content with More Source: https://github.com/bahamas10/bash-course/blob/main/notes/01-04-pager/readme.md The 'more' command is a simpler pager compared to 'less'. It allows viewing file content one screen at a time but typically only supports forward scrolling. It's a basic utility for examining text files. ```bash more /usr/share/dict/words ``` -------------------------------- ### Changing File Ownership and Permissions Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-04-file-permissions/readme.md This snippet introduces commands for changing file ownership and permissions in Bash. These commands are fundamental for system administration and collaborative development, allowing fine-grained control over who can access and modify files. It covers changing owner, group, and permissions. ```bash chown new_owner:new_group script.sh chmod permissions script.sh chgrp new_group script.sh ``` -------------------------------- ### Bash For Loop: Iterate Over Number Range (Brace Expansion) Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-04-for-loops/readme.md Iterates over a range of numbers from 1 to 5 using brace expansion and prints each number. ```bash for i in {1..5}; do echo "i is $i" done ``` -------------------------------- ### Bash: Read User Input from Stdin Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-01-taking-input/readme.md This snippet demonstrates how to prompt the user for input and store it in a variable using the 'read' command. It's useful for interactive scripts where specific data is needed from the user. ```bash read -p 'enter your name: ' name echo hello $name ``` -------------------------------- ### Bash: Redirecting Function Output (stdout and stderr) Source: https://github.com/bahamas10/bash-course/blob/main/notes/07-02-return-vs-output/readme.md Illustrates various methods for redirecting standard output (stdout) and standard error (stderr) from a Bash function. It shows how to capture specific streams into variables or discard them, and how to combine them. ```bash my-func() { echo this goes to stdout >&1 echo this goes to stderr >&2 return 0 } output=$(my-func) output=$(my-func 1>/dev/null) output=$(my-func 2>/dev/null) output=$(my-func 2>&1) output=$(my-func >/dev/null 2>&1) output=$(my-func 2>&1 >/dev/null) ``` -------------------------------- ### Managing Custom Variables Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-02-more-variables/readme.md Shows the syntax for assigning a value to a variable, printing that value, and removing the variable from the shell environment using the unset command. ```bash name=dave echo $name unset name ``` -------------------------------- ### List All Files in Directory with Bash Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-00-basic-globbing/readme.md Uses the '*' wildcard to list all files within the 'files/' directory. This is a fundamental globbing pattern for matching zero or more characters. ```bash ls files/ ``` ```bash echo files/* ``` ```bash printf '%s\n' files/* ``` ```bash ls -1 files/* ``` -------------------------------- ### Bash: Conditional User Input or Argument Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-01-taking-input/readme.md This snippet illustrates how to handle cases where a command-line argument might be provided or not. If an argument exists ('-n $1' checks if the first argument is non-empty), it's used; otherwise, the script prompts the user for input. ```bash if [[ -n $1 ]]; then name=$1 else read -p 'enter your name: ' name fi echo "Hello, $name" ``` -------------------------------- ### Bash Indexed Array Copying and Slicing Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-01-indexed-arrays/readme.md Demonstrates various methods for copying and creating sub-arrays (slices) from an existing Bash indexed array. This includes full copies, copies from a specific index, and copies of a range of elements. ```bash # array copy newarray=( "${array[@]}" ) # Full copy newarray=( "${array[@]:1}" ) # Copy from index 1 onwards newarray=( "${array[@]:0:2}" ) # Copy first 2 elements (index 0 and 1) ``` -------------------------------- ### Bash Array Manipulation with Parameter Expansion Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-00-parameter-expansion/readme.md Shows how to manipulate bash arrays using parameter expansion. This includes printing all elements, specific elements, and performing replacements or pattern matching on array elements. ```bash arr=(foo bar baz) printf '<%s>\n' "${arr[@]}" printf '<%s>\n' "${arr[@]:1:1}" printf '<%s>\n' "${arr[@]/a/1}" printf '<%s>\n' "${arr[@]#b}" printf '<%s>\n' "${arr[@]%z}" ``` -------------------------------- ### Bash: Conditionals and Control Flow Source: https://context7.com/bahamas10/bash-course/llms.txt Covers conditional statements in Bash, including string comparison, file existence checks using `[[ -f ]]`, and command success checks. It also demonstrates short-circuit evaluation with `&&`. ```bash #!/usr/bin/env bash # String comparison a=2 b=2 if [[ $a == $b ]]; then echo "they are the same" fi # File existence check if [[ -f /etc/passwd ]]; then echo "/etc/passwd is a file" fi # Command success check if apt-get update; then echo "if statement was true" else echo "if statement was false" fi # Short-circuit evaluation [[ -f /etc/passwd ]] && echo "it exists" ``` -------------------------------- ### List Files with Single Character Wildcard using Bash Globbing Source: https://github.com/bahamas10/bash-course/blob/main/notes/09-00-basic-globbing/readme.md Illustrates the use of the '?' wildcard, which matches exactly one character. 'ba?.txt' will match files like 'baz.txt' or 'bar.txt' but not 'batz.txt'. ```bash ls -1 files/ba?.txt ``` -------------------------------- ### Bash `for` Loops with Step Values in Brace Expansion Source: https://github.com/bahamas10/bash-course/blob/main/notes/10-02-braces-numeric/readme.md Illustrates using a step value within brace expansion in a `for` loop to generate sequences with increments. ```bash for i in {1..10..3}; do echo "$i" done ``` -------------------------------- ### Bash Indexed Array Declaration and Basic Access Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-01-indexed-arrays/readme.md Demonstrates how to declare an indexed array in Bash and access its elements. It shows accessing the entire array, individual elements by positive and negative indices, and using a variable for indexing. It also shows how to print all elements as a single string or as separate words. ```bash array=(foo bar baz) echo "$array" echo "${array[0]}" echo "${array[1]}" echo "${array[2]}" echo "${array[3]}" echo "${array[-1]}" item=2 echo "${array[item]}" echo "${array[$item]}" echo "${array[*]}" echo "${array[@]}" ``` -------------------------------- ### Configure Bash Shell Options Source: https://github.com/bahamas10/bash-course/blob/main/notes/15-01-customize-bashrc/readme.md Enables interactive shell options to improve directory navigation. 'cdspell' corrects minor typos in directory names, while 'autocd' allows changing directories by typing the directory name directly. ```bash shopt -s cdspell shopt -s autocd ``` -------------------------------- ### Handling Return Codes in Bash Functions Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-02-functions/readme.md Explains how to use the 'return' statement to exit a function with a specific status code and how to capture that code using the $? variable. ```bash my-func() { echo hi return 1 } my-func echo $? ``` -------------------------------- ### Check Associative Array Support in Bash Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-02-associative-arrays/readme.md Shows how to verify if the current shell environment supports associative arrays by checking the exit status of the declare command. ```bash if ! declare -A array; then echo "Associative arrays not supported" fi ``` -------------------------------- ### Bash Default Value Assignment Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-00-parameter-expansion/readme.md Illustrates how to assign default values to bash variables using parameter expansion. This is useful for handling unset or null variables, providing fallback values. ```bash name=$1 echo "hello $name!" echo 'done' ``` ```bash name=${1:-dave} name=${1:-$USER} name=${1?} name=${1?You must supply a name} name=${1:?} name=${1:?You must supply a name} ``` -------------------------------- ### Bash Variable Interpolation Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-00-actually-scripting/readme.md Demonstrates how to define variables and use them within strings using double quotes. This is useful for dynamic output based on user or system data. ```bash name='dave' echo "hello $name" ``` -------------------------------- ### Bash Character-by-Character String Iteration Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-00-parameter-expansion/readme.md Illustrates iterating through a string character by character in bash using parameter expansion and a for loop. This is useful for processing strings one character at a time. ```bash s='dave eddy' len=${#s} for ((i = 0; i < len; i++)); do c=${s:i:1} echo "$c" done ``` -------------------------------- ### Bash For Loop: Iterate Over String List Source: https://github.com/bahamas10/bash-course/blob/main/notes/03-04-for-loops/readme.md Iterates over a predefined list of strings (foo, bar, baz) and prints each string. ```bash for name in foo bar baz; do echo "name is $name" done ``` -------------------------------- ### Bash: Capturing Function Output and Return Code Source: https://github.com/bahamas10/bash-course/blob/main/notes/07-02-return-vs-output/readme.md Defines a simple Bash function that produces output to stdout and returns an exit code. It then shows how to call the function and inspect its return code. This is analogous to running a mini-program. ```bash my-func() { echo hello return 0 } my-func echo $? ``` -------------------------------- ### Bash Positional Parameter Expansion ($*) Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-01-array-expansion-chars/readme.md Illustrates how '$*' expands positional parameters into a single string. Without quotes, it's treated as one argument. With quotes, it's also treated as one argument but prevents word splitting. ```bash for arg in $*; do echo "<$arg>" done ``` ```bash for arg in "$*"; do echo "<$arg>" done ``` -------------------------------- ### Bash Array Inspection via CLI Source: https://github.com/bahamas10/bash-course/blob/main/notes/04-01-indexed-arrays/readme.md Shows how to inspect the declaration and content of a Bash array directly from the command line using the 'declare -p' command. This is useful for debugging and understanding array structure. ```bash declare -p array ``` -------------------------------- ### Bash Positional Parameter Expansion ($@) Source: https://github.com/bahamas10/bash-course/blob/main/notes/08-01-array-expansion-chars/readme.md Demonstrates how '$@' expands positional parameters into separate words. Without quotes, each parameter is a separate word. With quotes, each parameter remains a separate word, preserving spaces within parameters. ```bash for arg in $@; do echo "<$arg>" done ``` ```bash for arg in "$@"; do echo "<$arg>" done ``` -------------------------------- ### Find Program Location with 'which' Source: https://github.com/bahamas10/bash-course/blob/main/notes/02-01-programs-and-commands/readme.md The 'which' command locates the executable file for a given command. It searches the directories listed in the PATH environment variable. If the command is not found in the PATH, 'which' will not return a result. ```bash which ls which chmod which history ```