### Local Development Setup (Bash) Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/README.md Sets up a Python virtual environment, activates it, installs project dependencies using pip, and starts the MkDocs development webserver. This process is essential for editing and testing wiki content locally. ```bash python3 -m venv env source env/bin/activate pip install -r requirements.txt mkdocs serve ``` -------------------------------- ### Bash Process Substitution Examples and Bugs Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/expansion/proc_subst.md Provides examples illustrating potential bugs and portability considerations with Bash process substitution. The first example shows printing 'moo' using file descriptors, while the second demonstrates a fork bomb scenario. These examples highlight limitations and non-standard behavior. ```bash # print "moo" dev=fd=1 _[1<(echo moo >&2)]= # fork bomb ${dev[${dev='dev[1>(${dev[dev]})]'}]} ``` -------------------------------- ### Bash Simple Commands Examples Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/basicgrammar.md Demonstrates various ways to execute simple commands in Bash, including commands with arguments, output redirection, and environment variable manipulation. These examples illustrate the fundamental building blocks of Bash scripting. ```bash ls ls > list.txt ls -l LC_ALL=C ls ``` -------------------------------- ### Example: Using '--' with ls to list a file starting with a dash Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/dict/end_of_options.md Demonstrates how to use the '--' convention with the 'ls' command to correctly list a file named '-hello'. Without '--', 'ls' might interpret '-hello' as multiple options. ```bash ls -- -hello ``` -------------------------------- ### Bash 'select' Command Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/user_select.md An example demonstrating the use of the 'select' command to create a simple menu for ordering drinks. It includes clearing the screen, prompting the user, and using 'break' to exit the loop after a selection. ```bash clear echo echo hit number key 1 2 or 3 then ENTER-key echo ENTER alone is an empty choice and will loop endlessly until Ctrl-C or Ctrl-D echo select OPTIONX in beer whiskey wine liquor ; do echo you ordered a $OPTIONX break # break avoids endless loop -- second line to be executed always done ``` -------------------------------- ### Bash shift command example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/shift.md Demonstrates the 'shift' command's behavior in Bash. It shows how positional parameters are reordered and how the number of parameters ($#) is updated. This example highlights the core functionality of shifting parameters. ```bash # Example demonstrating the shift builtin command in bash # Set some initial positional parameters set -- This is a test # Print initial parameters and count echo "Initial parameters: $@" echo "Initial count: $#" # Shift parameters by 1 shift # Print parameters after shifting echo "After shift 1: $@" echo "After shift 1 count: $#" # Shift parameters by 2 shift 2 # Print parameters after shifting again echo "After shift 2: $@" echo "After shift 2 count: $#" ``` -------------------------------- ### printf Example: Dynamic Greeting Banner Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/printf.md Shows how to dynamically generate a greeting banner and assign it to a variable using `printf -v`. This example uses the `$LOGNAME` variable to personalize the greeting. ```bash printf -v GREETER "Hello %s" "$LOGNAME" echo "$GREETER" ``` -------------------------------- ### printf Examples: Number Formatting Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/printf.md Provides examples of using `printf` for various number formatting tasks. This includes printing decimal, octal, and hexadecimal representations, preserving signs, padding with zeros, and printing the ASCII code of a character. ```bash printf "%d\n" 0x41 printf "%d\n" -0x41 printf "%+d\n" 0x41 printf "%o\n" 65 printf "%05o\n" 65 printf "%d\n" 'A printf "%d\n" "'A" ``` -------------------------------- ### Bash I/O Redirection Examples Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/redirection_tutorial.md Demonstrates correct and incorrect usage of Bash I/O redirection operators. It highlights how to group redirections for clarity and avoid ambiguous syntax. ```bash # Good! This is clearly a simple commmand with two arguments and 4 redirections cmd arg1 arg2 /dev/null >&2 # Good! { cmd1 <<<'my input'; cmd2; } >someFile # Bad. Is the "1" a file descriptor or an argument to cmd? (answer: it's the FD). Is the space after the herestring part of the input data? (answer: No). # The redirects are also not delimited in any obvious way. cmd 2>& 1 <<< stuff # Hideously Bad. It's difficult to tell where the redirects are and whether they're even valid redirects. # This is in fact one command with one argument, an assignment, and three redirects. foo=barbleh ``` -------------------------------- ### Bash: Shebang Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/style.md Demonstrates the use of a shebang line in a Bash script to specify the interpreter. It emphasizes using `bash` for Bash scripts and `sh` for POSIX-compliant scripts, warning against the misconception that `/bin/sh` is always Bash on Linux. ```bash #!/bin/bash # Script content here... ``` -------------------------------- ### Ksh coproc: Traditional workaround for pipeline subshell Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/keywords/coproc.md This example illustrates the traditional way to handle pipeline subshells in Ksh (ksh93, mksh, pdksh derivatives) using the coprocess feature. It starts a coprocess with 'ls' and then reads its output line by line within a 'while read' loop. ```bash # ksh93 or mksh/pdksh derivatives ls |& # start a coprocess while IFS= read -rp file; do print -r -- "$file"; done # read its output ``` -------------------------------- ### Bash let command example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/let.md Demonstrates the usage of the 'let' command for arithmetic operations and variable assignments, showing its output and return code. ```bash $ let 'b = a' "(a += 3) + $((a = 1)), b++" $ echo "$a - $b - $?" 4 - 2 - 0 ``` -------------------------------- ### printf as echo Replacement Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/printf.md Shows how `printf` can be used as a replacement for the `echo` command. The first example demonstrates the equivalent of `/usr/bin/echo` using `printf "%b\n" "$*"`. The second example shows the logic for `/usr/ucb/echo`. ```bash # Equivalent to /usr/bin/echo printf "%b\n" "$*" # Equivalent to /usr/ucb/echo if [ "X$1" = "X-n" ] then shift printf "%s" "$*" else printf "%s\n" "$*" fi ``` -------------------------------- ### Bash: Using Prefixes for Uppercase Variables Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/style.md Demonstrates how to safely use uppercase variable names in Bash by prepending a unique prefix. This avoids conflicts with reserved system variables. The example shows iterating through log files in a specified directory. ```bash #!/bin/bash # the prefix 'MY_' MY_LOG_DIRECTORY=/var/adm/ for file in "$MY_LOG_DIRECTORY"/*; do echo "Found Logfile: $file" done ``` -------------------------------- ### Running Bashtests Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/testing-your-scripts.md Commands to install and run bashtests. The 'pip install bashtest' command installs the necessary tool, and 'bashtest *.bashtest' executes all test files in the current directory. The output indicates the number of passed tests. ```bash # install bashtest if required! $ pip install bashtest # run tests $ bashtest *.bashtest 1 items passed all tests: 1 tests in tests.bashtest 1 tests in 1 items. 1 passed and 0 failed. Test passed. ``` -------------------------------- ### Bash read command example with array assignment Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/read.md Illustrates reading input word-wise into a specified array using the '-a' option. This example shows how to safely assign to array elements by quoting the array name and index to prevent pathname expansion. ```bash read -a MYARRAY <<<"word1 word2 word3" printf '%s\n' "${MYARRAY[0]}" "${MYARRAY[1]}" "${MYARRAY[2]}" ``` ```bash read 'MYARRAY[1]' <<<"some value" ``` -------------------------------- ### Bash C-style for-loop Stepping Counter Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/c_for.md Illustrates a C-style for-loop in Bash with a stepping counter. This example increments the counter by a specified step (10 in this case) in each iteration, counting from 0 to 100. ```bash for ((x = 0 ; x <= 100 ; x += 10)); do echo "Counter: $x" done ``` -------------------------------- ### Pathname Expansion (Globbing) Examples in Bash Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/expansion/intro.md Provides examples of pathname expansion, also known as globbing. Bash uses these patterns to match filenames in the current directory. This occurs after word splitting, making it safe for filenames with spaces. ```bash *.txt ``` ```bash page_1?.html ``` -------------------------------- ### Bash Case Statement Example: Fruit Selection Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/case.md An example demonstrating the use of the 'case' statement to handle user input for selecting a fruit. It includes handling multiple patterns with the '|' operator and a default case. ```bash printf '%s ' 'Which fruit do you like most?' read -${BASH_VERSION+e}r fruit case $fruit in apple) echo 'Mmmmh... I like those!' ;; banana) echo 'Hm, a bit awry, no?' ;; orange|tangerine) echo $'Eeeks! I don't like those!\nGo away!' exit 1 ;; *) echo "Unknown fruit - sure it isn't toxic?" esac ``` -------------------------------- ### Bash C-style for-loop Simple Counter Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/c_for.md A basic example of a C-style for-loop in Bash, demonstrating a simple counter that iterates from 0 to 100, printing the current value in each iteration. It clearly shows initialization, condition checking, and incrementing. ```bash for ((x = 0 ; x <= 100 ; x++)); do echo "Counter: $x" done ``` -------------------------------- ### Bash for loop over number range (brace expansion) Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/classic_for.md Shows how to use Bash 4+ brace expansion for looping over a range of numbers. The first example creates numbers from 0 to 99. The second example shows how to specify a step and create numbers with leading zeros. ```bash # 100 numbers, no leading zeroes for x in {0..99}; do echo $x done # Every other number, width 3 for x in {000..99..2}; do echo $x done ``` -------------------------------- ### printf Example: Right-Align Text Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/printf.md Demonstrates how to print text aligned to the right end of the line using `printf`. It utilizes `tput cols` to get the current terminal width and the `%*s` format specifier for dynamic field width. ```bash printf "%*s\n" $(tput cols) "Hello world!" ``` -------------------------------- ### Bash: Basic Script Structure Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/style.md Presents the fundamental organization of a Bash script, starting with the shebang, followed by configuration variables, function definitions, and finally the main execution code. This structure promotes readability and maintainability. ```bash #!SHEBANG CONFIGURATION_VARIABLES FUNCTION_DEFINITIONS MAIN_CODE ``` -------------------------------- ### Getting Current Script/Function Line Number with LINENO Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/shellvars.md LINENO is an integer variable. Each time it is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function. Its value is not guaranteed to be meaningful when not in a script or function. ```bash echo "This is line number: $LINENO" ``` -------------------------------- ### Bash: Kill Background Job with Termination Message Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/snipplets/kill_bg_job_without_message.md This bash script demonstrates starting a background job, getting its PID, and then killing it. It shows the typical termination message that appears when the shell reports the job's end. ```bash #!/bin/bash # example background process sleep 300 & # get the PID BG_PID=$! # kill it, hard and mercyless kill -9 $BG_PID echo "Yes, we killed it" ``` -------------------------------- ### Bash Script Execution Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/basics.md Demonstrates how to execute a Bash script file. The script can be run directly using the 'bash' command followed by the filename, or if made executable, by calling the filename directly after setting execute permissions. ```bash bash ./myfile chmod +x ./myfile ``` -------------------------------- ### Bash: Quoting Parameter Expansion Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/style.md Highlights the necessity of quoting parameter expansions in Bash to prevent word splitting and unexpected behavior. It notes exceptions but advises quoting for safety. The example shows a loop where unquoted expansion is required to iterate over words. ```bash list="one two three" # you MUST NOT quote $list here for word in $list; do ... done ``` -------------------------------- ### Bash getopts Basic Example with Silent Error Handling Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/getopts_tutorial.md This script demonstrates the basic usage of `getopts` in bash to parse a single option '-a' without arguments. It utilizes silent error reporting by prefixing the option string with a colon, allowing custom handling of invalid options. ```bash #!/bin/bash while getopts ":a" opt; do case $opt in a) echo "-a was triggered!" >&2 ;; \?) echo "Invalid option: -$OPTARG" >&2 ;; esac done ``` -------------------------------- ### Indentation for Long Options in Bash Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/style.md Demonstrates two methods for breaking long lines of code when using command options. The first aligns subsequent lines with the start of the option, while the second uses a two-space indentation. This aids in visually grouping related options. ```bash activate some_very_long_option \ some_other_option ``` ```bash activate some_very_long_option \ some_other_option ``` -------------------------------- ### Brace Expansion Examples in Bash Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/expansion/intro.md Demonstrates brace expansion, which generates arbitrary strings. It can create lists of strings, sequences of numbers, or ranges. This is one of the first expansions performed by Bash. ```bash {X,Y,Z} ``` ```bash {X..Y} ``` ```bash {X..Y..Z} ``` -------------------------------- ### Bash coproc: Redirecting stderr in a pipe Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/keywords/coproc.md This example demonstrates how to redirect the standard error of a coprocess to its standard output, allowing it to be captured within the same pipe. It uses 'read' to capture the output and 'printf' to display it. The coprocess is started with 'coproc', and its stderr is redirected to stdout using '2>&1'. ```bash # redirecting stderr in the pipe $ coproc { ls thisfiledoesntexist; read; } 2>&1 [2] 23084 $ IFS= read -ru ${COPROC[0]} x; printf '%s\n' "$x" ls: cannot access thisfiledoesntexist: No such file or directory ``` -------------------------------- ### Bash Named Coprocess Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/keywords/coproc.md Demonstrates the usage of a named coprocess in Bash. It shows how to define a coprocess, send data to it, read data from it, and then terminate it. The coprocess is assigned to an indexed array named 'mycoproc'. ```bash $ coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} [1] 23058 $ echo bar >&${mycoproc[1]} $ IFS= read -ru ${mycoproc[0]} x; printf '%s\n' "$x" foobar $ kill $mycoproc_PID $ [1]+ Terminated coproc mycoproc { awk '{print "foo" $0;fflush()}'; } ``` -------------------------------- ### Bash read command example with REPLY variable Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/read.md Demonstrates how the 'read' command assigns the entire line to the REPLY variable when no variable names are provided. This preserves leading/trailing spaces and other characters as read. ```bash while read -r; do printf '"%s"\n' "$REPLY" done <<<" a line with prefix and postfix space " ``` -------------------------------- ### Bash coproc: Pitfall - Avoid final pipeline subshell (doesn't work) Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/keywords/coproc.md This Bash example demonstrates a common pitfall when trying to replicate the Ksh coprocess workaround for pipeline subshells. It attempts to start 'ls' as a coprocess and read its output, but fails because the file descriptor is closed by the time 'read' is called. ```bash #DOESN'T WORK $ coproc ls [1] 23232 $ while IFS= read -ru ${COPROC[0]} line; do printf '%s\n' "$line"; done bash: read: line: invalid file descriptor specification [1]+ Done coproc COPROC ls ``` -------------------------------- ### Bash nested for-loops example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/classic_for.md An example of nested for loops in Bash, where an inner loop is executed for each iteration of an outer loop. This specific example counts from 00 to 99. ```bash for x in 0 1 2 3 4 5 6 7 8 9; do for y in 0 1 2 3 4 5 6 7 8 9; do echo $x$y done done ``` -------------------------------- ### Bash Parameter Expansion Examples Source: https://context7.com/flokoe/bash-hackers-wiki/llms.txt Demonstrates various parameter expansion techniques in Bash for retrieving and manipulating variable values. This includes substring extraction, default value handling, substring removal, search and replace, case modification, and indirection. ```bash # Basic parameter expansion WORD="hello" echo "${WORD}world" # helloworld - prevents variable name ambiguity # String length MYSTRING="Be liberal in what you accept" echo "${#MYSTRING}" # 30 # Substring extraction (offset:length) echo "${MYSTRING:3:7}" # liberal echo "${MYSTRING: -6}" # accept (negative offset from end, note the space) # Default values echo "${UNDEFINED:-default}" # default (use default if unset/empty) echo "${UNDEFINED:=default}" # default (assign default if unset/empty) # Substring removal - filename manipulation FILEPATH="/home/user/document.txt" echo "${FILEPATH##*/}" # document.txt (remove path - longest match from start) echo "${FILEPATH%.*}" # /home/user/document (remove extension) echo "${FILEPATH%%/*}" # (empty - removes everything after first /) # Search and replace TEXT="hello world world" echo "${TEXT/world/universe}" # hello universe world (first match) echo "${TEXT//world/universe}" # hello universe universe (all matches) # Case modification (Bash 4+) NAME="john doe" echo "${NAME^}" # John doe (capitalize first char) echo "${NAME^^}" # JOHN DOE (uppercase all) echo "${NAME,,}" # john doe (lowercase all) # Indirection - variable containing variable name ref="MYSTRING" echo "${!ref}" # Be liberal in what you accept ``` -------------------------------- ### Expand a Range of Positional Parameters Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/posparams.md Shows how to expand a specific range of positional parameters using `${@:START:COUNT}` and `${*:START:COUNT}`. This allows for selecting a subset of arguments, including negative start indices and omitting the count to expand to the end. ```bash # Example: Echo all parameters starting from the second one echo "${@:2}" # Example: Echo 2 parameters starting from the last one echo "${@: -1:2}" # Example: Echo all parameters starting from the last one echo "${@: -1}" ``` -------------------------------- ### Bash: Variable Initialization Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/style.md Illustrates the importance of initializing variables in Bash to prevent unexpected behavior and potential security issues from environment variable injection. Shows initialization for a string, an array, and a number. ```bash my_input="" my_array=() my_number=0 ``` -------------------------------- ### List all installed traps Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/trap.md Executes the 'trap' command without any arguments to display a list of all currently installed trap handlers in a reusable format. ```bash trap ``` -------------------------------- ### Bash: Read from a file using a separate file descriptor with exec Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/redirection_tutorial.md This example shows how to use 'exec' to open a file ('file') with a new file descriptor (3) for reading. This allows reading from the file independently of standard input, which is crucial for interactive loops that also need to read from the terminal. ```bash exec 3( COMMAND ) ``` -------------------------------- ### Bash Pipe Example: Connecting Command Output to Input Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/redirection_tutorial.md Demonstrates the use of the pipe symbol (|) in Bash to connect the standard output of one command to the standard input of another. This allows for chaining commands, where the output of the left command becomes the input for the right command. The shell sets up a pipe file descriptor before executing the commands. ```bash echo foo | cat ``` -------------------------------- ### Bash printf -v Assignment Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/printf.md This example demonstrates the use of the `printf -v` option in Bash to assign formatted output directly to a variable. It contrasts with command substitution, which strips trailing newlines. ```bash # Illustrates Bash-like behavior. Redefining printf is usually unnecessary / not recommended. function printf { case $1 in -v) shift nameref x=$1 shift x=$(command printf "$@") ;; *) command printf "$@" esac } builtin cut print $$ printf -v 'foo[2]' '%d\n' "$(cut -d ' ' -f 1 /proc/self/stat)" typeset -p foo # 22461 # typeset -a foo=([2]=22461) ``` -------------------------------- ### Bash Shebang Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/dict/interpreter_directive.md This is a standard example of a shebang line for a Bash script. It specifies that the script should be executed using the Bash interpreter located at /bin/bash. The line is ignored by the shell as it's a comment. ```bash #!/bin/bash ``` -------------------------------- ### Bash Process Substitution Syntax Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/expansion/proc_subst.md Demonstrates the basic syntax for process substitution in Bash, showing how to redirect standard output of a command as a file descriptor. ```bash $ echo <(ls) /dev/fd/63 ``` -------------------------------- ### Bash let command with local environment demonstration Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/let.md Illustrates how 'let' operates within its own environment, making variable assignments effectively local to the builtin unless otherwise modified. ```bash ~ $ ( y=1+1 let x=y; declare -p x y ) declare -- x="2" bash: declare: y: not found ~ $ ( y=1+1 let x=y++; declare -p x y ) declare -- x="2" declare -- y="3" ``` -------------------------------- ### Bash `read` Builtin Examples Source: https://context7.com/flokoe/bash-hackers-wiki/llms.txt Demonstrates the usage of the `read` builtin command in Bash for reading input from stdin or file descriptors into variables. Covers options for prompts, silent input, timeouts, single characters, arrays, custom delimiters (IFS), and reading from files. ```bash # Basic read into variable echo "Enter name:"; read -r name echo "Hello, $name" # Read with prompt read -rp "Enter your age: " age # Read password (silent input) read -rsp "Password: " password; echo # Read with timeout (5 seconds) if read -rt 5 -p "Quick! Enter code: " code; then echo "Code: $code" else echo "Timeout!" fi # Read single character read -rn 1 -p "Continue? (y/n) " answer; echo # Read into array read -ra words <<< "one two three four" echo "${words[1]}" # two # Read with custom delimiter (IFS) IFS=":" read -r user pass uid gid gecos home shell <<< "root:x:0:0:root:/root:/bin/bash" echo "User: $user, Home: $home" # Read file line by line (preserving whitespace) while IFS= read -r line; do echo "Line: $line" done < /etc/passwd # Read from file descriptor exec 3< /etc/hosts while read -ru 3 line; do echo "$line" done exec 3<&- # Close file descriptor ``` -------------------------------- ### Source Configuration File in Bash Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/conffile.md Demonstrates how to load variables from a configuration file into the current Bash script using the 'source' command. Assumes the config file is formatted as key="value". ```bash #!/bin/bash echo "Reading config...." >&2 source /etc/cool.cfg echo "Config for the username: $cool_username" >&2 echo "Config for the target host: $cool_host" >&2 ``` -------------------------------- ### Bash Group Command File Descriptor Example Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/grouping_plain.md Illustrates how file descriptors are cumulative when using group commands. This example redirects the standard output of multiple commands within the group to a single file named 'output.txt'. ```bash { echo "PASSWD follows" cat /etc/passwd echo echo "GROUPS follows" cat /etc/group } >output.txt ``` -------------------------------- ### Bash 'select' Command Syntax Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/ccmd/user_select.md Demonstrates the different syntaxes for the Bash 'select' command, including the standard 'do...done' loop and the alternative '{...}' block. The '{...}' syntax is undocumented and not POSIX-compliant. ```bash select ; do done select in ; do done # alternative, historical and undocumented syntax select { } select in { } ``` -------------------------------- ### Per-User Configuration Override in Bash Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/howto/conffile.md Illustrates how to load a system-wide configuration file and then optionally override its settings with a user-specific configuration file if it exists. Uses the '.' command for sourcing. ```bash #!/bin/bash echo "Reading system-wide config...." >&2 . /etc/cool.cfg if [ -r ~/.coolrc ]; then echo "Reading user config...." >&2 . ~/.coolrc fi ``` -------------------------------- ### Bash: Execute a program with exec Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/commands/builtin/exec.md This example demonstrates how to use the 'exec' command in bash to replace the current shell process with another program, passing along any arguments. It's useful for creating wrapper scripts. ```bash myprog=/bin/ls echo "This is the wrapper script, it will exec $myprog" # do some vodoo here, probably change the arguments etc. # well, stuff a wrapper is there for exec "$myprog" "$@" ``` -------------------------------- ### Create Subdirectory Structure with Brace Expansion Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/syntax/expansion/brace.md Illustrates using brace expansion with the `mkdir` command to quickly create multiple directories with specified names. This is useful for setting up project structures or temporary directories. ```bash mkdir /home/bash/test/{foo,bar,baz,cat,dog} ``` -------------------------------- ### Check Command Availability using 'hash' (Bash) Source: https://github.com/flokoe/bash-hackers-wiki/blob/main/docs/scripting/nonportable.md Demonstrates how to check if a command is available in the system's PATH using the 'hash' command. It includes examples for checking a single command and iterating through a list of commands to ensure their availability. ```bash if hash ls >/dev/null 2>&1; then echo "ls is available" fi ``` ```bash for name in ls grep sed awk; do if ! hash "$name" >/dev/null 2>&1; then echo "FAIL: Missing command '$name'" exit 1 fi done ```