Skip to content

Instantly share code, notes, and snippets.

@cisoun
Last active August 13, 2024 11:57
Show Gist options
  • Save cisoun/eb9923cddbe3a3177d6a926009cc5674 to your computer and use it in GitHub Desktop.
Save cisoun/eb9923cddbe3a3177d6a926009cc5674 to your computer and use it in GitHub Desktop.
How2Bash

How2Bash

A collection of useful tips in bash.

Streams

Redirections

command >/dev/null # Silent all output.
command 2>&1 # Redirect errors to output (stderr to stdout).
command 2>&2 2>file # Redirect errors to stderr AND a file.

System

Environment

# Check if an environment variable exists.
# check_env "PATH"
function check_env() {
	if [[ -z $(eval "echo \$$1") ]]; then
		echo "$1 undefined"
	fi
}

Types

Arrays

To single line:   ($(multiline))
Element by index: ${array[N]}
First element:    ${array}
Flatten:          ${array[@]}
Length:           ${#array[@]}
Subarray:         ${array:FROM}
Subarray:         ${array:FROM:TO}

For loops

# Without iterator.
for $item in "${array[@]}"; do
	echo $item
done

# With iterator.
for (( i = 0; i < ${#array[@]}; i++ )); do
	echo "${item[$i]}"
done

IndexOf

# Usage:   indexof <item> <array>
# Example: indexof "hello" $array
# Return:  position of ITEM in ARRAY or fail

indexof() {
	local item=$1
	local array=$2
	local length=${#array[@]}

	for (( i = 0; i < $length; i++ )); do
		if [[ $item = ${array[$i]} ]]; then
			echo $i
			return 0
		fi
	done

	return 1
}

Numbers

Operations:         $(($a + 2))
Operations (reals): $(($a + 2.0))
Range:              $(seq $TO) # 0 to $TO
Range:              $(seq $FROM $TO) # $(seq 0 100)

Strings

Length:                     ${#text}
Substring:                  ${text:FROM:TO}
Substring (from beginning): ${text:FROM}
Substring (from ending):    ${text: -FROM} # Space is necessary !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment