diff --git a/modules/bash-commons/src/assert.sh b/modules/bash-commons/src/assert.sh index 4ec6028..1e767e3 100644 --- a/modules/bash-commons/src/assert.sh +++ b/modules/bash-commons/src/assert.sh @@ -91,7 +91,7 @@ function assert_exactly_one_of { # Determine how many arg_vals are non-empty for (( i=0; i<$((num_args)); i+=2 )); do arg_names+=("${args[i]}") - if [[ ! -z "${args[i+1]}" ]]; then + if [[ -n "${args[i+1]}" ]]; then num_non_empty=$((num_non_empty+1)) fi done @@ -108,4 +108,12 @@ function assert_uid_is_root_or_sudo { log_error "This script should be run using sudo or as the root user" exit 1 fi -} \ No newline at end of file +} + +# Assert that the user running this script has permissions to run sudo. +function assert_user_has_sudo_perms { + if ! sudo -n true >/dev/null 2>&1; then + log_error "This script should be run using sudo, as the root user, or as a user with sudo permissions." + exit 1 + fi +} diff --git a/modules/bash-commons/src/string.sh b/modules/bash-commons/src/string.sh index a7eca79..40467eb 100644 --- a/modules/bash-commons/src/string.sh +++ b/modules/bash-commons/src/string.sh @@ -56,3 +56,32 @@ function string_is_empty_or_null { local -r response="$1" [[ -z "$response" || "$response" == "null" ]] } + + +# Given a string $str, return the substring beginning at index $start and ending at index $end. +# +# Example: +# +# string_substr "hello world" 0 5 +# Returns "hello" +function string_substr { + local -r str="$1" + local -r start="$2" + local end="$3" + + if [[ "$start" -lt 0 || "$end" -lt 0 ]]; then + log_error "In the string_substr bash function, each of \$start and \$end must be >= 0." + exit 1 + fi + + if [[ "$start" -gt "$end" ]]; then + log_error "In the string_substr bash function, \$start must be < \$end." + exit 1 + fi + + if [[ -z "$end" ]]; then + end="${#str}" + fi + + echo "${str:$start:$end}" +} diff --git a/test/string.bats b/test/string.bats index 05526cf..aa84011 100644 --- a/test/string.bats +++ b/test/string.bats @@ -186,4 +186,13 @@ load "test-helper" assert_failure } +@test "string_substr empty string" { + run string_substr "" 0 0 + assert_success +} +@test "string_substr non empty string" { + run string_substr "hello world" 0 5 + assert_success + assert_output "hello" +}