added examples

This commit is contained in:
Dylan Araps
2018-06-15 09:29:43 +10:00
parent ac2b9e7ddf
commit 9f43812680
3 changed files with 197 additions and 61 deletions

View File

@@ -4,5 +4,5 @@ os:
- linux - linux
script: script:
- shellcheck -s bash --exclude=SC2034,SC2154 <(awk '/```sh/{f=1;next}/```/{f=0}f' README.md) - shellcheck -s bash --exclude=SC2034,SC2154 <(awk '/```sh$/{f=1;next}/```/{f=0}f' README.md)
- ./test.sh - ./test.sh

218
README.md
View File

@@ -104,6 +104,8 @@ scripts and not full blown utilities.
### Trim leading and trailing white-space from string. ### Trim leading and trailing white-space from string.
**Example Function:**
```sh ```sh
trim_string() { trim_string() {
# Usage: trim_string " example string " # Usage: trim_string " example string "
@@ -113,12 +115,26 @@ trim_string() {
} }
``` ```
**Example Usage:**
```shell
$ trim_string " Hello, World "
Hello, World
$ name=" John Black "
$ trim_string "$name"
John Black
```
### Trim all white-space from string and truncate spaces. ### Trim all white-space from string and truncate spaces.
**Example Function:**
```sh ```sh
# shellcheck disable=SC2086,SC2048 # shellcheck disable=SC2086,SC2048
trim_all() { trim_all() {
# Usage: trim " example string " # Usage: trim_all " example string "
set -f set -f
set -- $* set -- $*
printf '%s\n' "$*" printf '%s\n' "$*"
@@ -126,6 +142,17 @@ trim_all() {
} }
``` ```
**Example Usage:**
```shell
$ trim_all " Hello, World "
Hello, World
$ name=" John Black is my name. "
$ trim_all "$name"
John Black is my name.
```
### Use REGEX on a string. ### Use REGEX on a string.
We can use the result of `bash`'s regex matching to create a simple `sed` We can use the result of `bash`'s regex matching to create a simple `sed`
@@ -138,55 +165,68 @@ Stick to POSIX regex features if aiming for compatibility.
**NOTE**: This example only prints the first matching group. When using **NOTE**: This example only prints the first matching group. When using
multiple capture groups some modification will be needed. multiple capture groups some modification will be needed.
**Example Function:**
```sh ```sh
regex() { regex() {
# Usage: regex "string" "regex" # Usage: regex "string" "regex"
[[ $1 =~ $2 ]] && printf '%s\n' "${BASH_REMATCH[1]}" [[ $1 =~ $2 ]] && printf '%s\n' "${BASH_REMATCH[1]}"
} }
```
# Example: **Example Usage:**
# Trim leading white-space.
: regex ' hello' '^\s*(.*)'
```shell
$ # Trim leading white-space.
$ regex ' hello' '^\s*(.*)'
hello
# Example script usage (Validate hex colors): $ # Validate a hex color.
_() { $ regex "#FFFFFF" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$'
colors=( #FFFFFF
"#FFFFFF"
"#000000"
"#CDEFDC"
"#12dlks"
"red"
)
for color in "${colors[@]}"; do $ # Validate a hex color (invalid).
if [[ "$color" =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then $ regex "red" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$'
# no output (invalid)
```
**Example Usage in script:**
```shell
is_hex_color() {
if [[ "$1" =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then
printf '%s\n' "${BASH_REMATCH[1]}" printf '%s\n' "${BASH_REMATCH[1]}"
else else
printf '%s\n' "error: $color is an invalid color." printf '%s\n' "error: $1 is an invalid color."
return 1
fi fi
done
} }
read -r color
is_hex_color "$color" || color="#FFFFFF"
# Do stuff.
``` ```
### Split a string on a delimiter. ### Split a string on a delimiter.
```sh ```shell
_() {
# To multiple variables.
string="1,2,3" string="1,2,3"
# To multiple variables.
IFS=, read -r var1 var2 var3 <<< "$string" IFS=, read -r var1 var2 var3 <<< "$string"
# To an array. # To an array.
IFS=, read -ra vars <<< "$string" IFS=, read -ra vars <<< "$string"
}
``` ```
### Change a string to lowercase. ### Change a string to lowercase.
**NOTE:** Requires `bash` 4+ **NOTE:** Requires `bash` 4+
**Example Function:**
```sh ```sh
lower() { lower() {
# Usage: lower "string" # Usage: lower "string"
@@ -194,10 +234,25 @@ lower() {
} }
``` ```
**Example Usage:**
```shell
$ lower "HELLO"
hello
$ lower "HeLlO"
hello
$ lower "hello"
hello
```
### Change a string to uppercase. ### Change a string to uppercase.
**NOTE:** Requires `bash` 4+ **NOTE:** Requires `bash` 4+
**Example Function:**
```sh ```sh
upper() { upper() {
# Usage: upper "string" # Usage: upper "string"
@@ -205,8 +260,23 @@ upper() {
} }
``` ```
**Example Usage:**
```shell
$ upper "hello"
HELLO
$ upper "HeLlO"
HELLO
$ upper "HELLO"
HELLO
```
### Trim quotes from a string. ### Trim quotes from a string.
**Example Function:**
```sh ```sh
trim_quotes() { trim_quotes() {
# Usage: trim_quotes "string" # Usage: trim_quotes "string"
@@ -215,42 +285,63 @@ trim_quotes() {
} }
``` ```
**Example Usage:**
```shell
$ var="'Hello', \"World\""
$ trim_quotes "$var"
Hello, World
```
### Strip all instances of pattern from string. ### Strip all instances of pattern from string.
**Example Function:**
```sh ```sh
strip_all() { strip_all() {
# Usage: strip_all "string" "pattern" # Usage: strip_all "string" "pattern"
printf '%s\n' "${1//$2}" printf '%s\n' "${1//$2}"
} }
```
# Examples: **Example Usage:**
# Output: "Th Qck Brwn Fx" ```shell
: strip_all "The Quick Brown Fox" "[aeiou]" $ strip_all "The Quick Brown Fox" "[aeiou]"
Th Qck Brwn Fx
# Output: "TheQuickBrownFox" $ strip_all "The Quick Brown Fox" "[[:space:]]"
: strip_all "The Quick Brown Fox" "[[:space:]]" TheQuickBrownFox
$ strip_all "The Quick Brown Fox" "Quick "
The Brown Fox
``` ```
### Strip first occurrence of pattern from string. ### Strip first occurrence of pattern from string.
**Example Function:**
```sh ```sh
strip() { strip() {
# Usage: strip "string" "pattern" # Usage: strip "string" "pattern"
printf '%s\n' "${1/$2}" printf '%s\n' "${1/$2}"
} }
```
# Examples: **Example Usage:**
# Output: "Th Quick Brown Fox" ```shell
: strip_all "The Quick Brown Fox" "[aeiou]" $ strip "The Quick Brown Fox" "[aeiou]"
Th Quick Brown Fox
# Output: "TheQuick Brown Fox" $ strip "The Quick Brown Fox" "[[:space:]]"
: strip_all "The Quick Brown Fox" "[[:space:]]" TheQuick Brown Fox
``` ```
### Strip pattern from start of string. ### Strip pattern from start of string.
**Example Function:**
```sh ```sh
lstrip() { lstrip() {
# Usage: lstrip "string" "pattern" # Usage: lstrip "string" "pattern"
@@ -258,8 +349,17 @@ lstrip() {
} }
``` ```
**Example Usage:**
```shell
$ lstrip "The Quick Brown Fox" "The "
Quick Brown Fox
```
### Strip pattern from end of string. ### Strip pattern from end of string.
**Example Function:**
```sh ```sh
rstrip() { rstrip() {
# Usage: rstrip "string" "pattern" # Usage: rstrip "string" "pattern"
@@ -267,12 +367,18 @@ rstrip() {
} }
``` ```
**Example Usage:**
```shell
$ rstrip "The Quick Brown Fox" " Fox"
The Quick Brown
```
## Variables ## Variables
### Assign and access a variable using a variable. ### Assign and access a variable using a variable.
```sh ```shell
_() {
hello_world="test" hello_world="test"
# Create the variable name. # Create the variable name.
@@ -281,7 +387,6 @@ _() {
# Print the value of the variable name stored in 'hello_$var1'. # Print the value of the variable name stored in 'hello_$var1'.
printf '%s\n' "${!var2}" printf '%s\n' "${!var2}"
}
``` ```
@@ -292,16 +397,34 @@ _() {
Enabling `extdebug` allows access to the `BASH_ARGV` array which stores Enabling `extdebug` allows access to the `BASH_ARGV` array which stores
the current functions arguments in reverse. the current functions arguments in reverse.
**Example Function:**
```sh ```sh
reverse_array() { reverse_array() {
# Usage: reverse_array "array" # Usage: reverse_array "array"
# reverse_array 1 2 3 4 5 6
shopt -s extdebug shopt -s extdebug
f()(printf '%s\n' "${BASH_ARGV[@]}"); f "$@" f()(printf '%s\n' "${BASH_ARGV[@]}"); f "$@"
shopt -u extdebug shopt -u extdebug
} }
``` ```
**Example Usage:**
```shell
$ reverse_array 1 2 3 4 5
5
4
3
2
1
$ arr=(red blue green)
$ reverse_array "${arr[@]}"
green
blue
red
```
### Remove duplicate array elements. ### Remove duplicate array elements.
Create a temporary associative array. When setting associative array Create a temporary associative array. When setting associative array
@@ -310,6 +433,8 @@ allows us to effectively remove array duplicates.
**NOTE:** Requires `bash` 4+ **NOTE:** Requires `bash` 4+
**Example Function:**
```sh ```sh
remove_array_dups() { remove_array_dups() {
# Usage: remove_array_dups "array" # Usage: remove_array_dups "array"
@@ -323,6 +448,21 @@ remove_array_dups() {
} }
``` ```
```shell
$ remove_array_dups 1 1 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
1
2
3
4
5
$ arr=(red red green blue blue)
$ remove_array_dups "${arr[@]}"
red
green
blue
```
### Cycle through an array. ### Cycle through an array.
Each time the `printf` is called, the next array element is printed. When Each time the `printf` is called, the next array element is printed. When
@@ -360,24 +500,20 @@ cycle() {
Alternative to the `cat` command. Alternative to the `cat` command.
```sh ```shell
_() {
file_data="$(<"file")" file_data="$(<"file")"
}
``` ```
### Read a file to an array (*by line*). ### Read a file to an array (*by line*).
Alternative to the `cat` command. Alternative to the `cat` command.
```sh ```shell
_() {
# Bash <4 # Bash <4
IFS=$'\n' read -d "" -ra file_data < "file" IFS=$'\n' read -d "" -ra file_data < "file"
# Bash 4+ # Bash 4+
mapfile -t file_data < "file" mapfile -t file_data < "file"
}
``` ```
### Get the first N lines of a file. ### Get the first N lines of a file.

View File

@@ -138,7 +138,7 @@ assert_equals() {
} }
main() { main() {
source <(awk '/```sh/{f=1;next}/```/{f=0}f' README.md) 2>/dev/null source <(awk '/```sh$/{f=1;next}/```/{f=0}f' README.md) 2>/dev/null
head="-> Running tests on the Pure Bash Bible.." head="-> Running tests on the Pure Bash Bible.."
printf '\n%s\n%s\n' "$head" "${head//?/-}" printf '\n%s\n%s\n' "$head" "${head//?/-}"