Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions modules/bash-commons/src/assert.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
}

# 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
}
29 changes: 29 additions & 0 deletions modules/bash-commons/src/string.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
9 changes: 9 additions & 0 deletions test/string.bats
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}