Skip to content

Instantly share code, notes, and snippets.

@mechalynx
Last active September 16, 2017 15:11
Show Gist options
  • Save mechalynx/0c8864c940ed92a16f8c0ca2204c5cf7 to your computer and use it in GitHub Desktop.
Save mechalynx/0c8864c940ed92a16f8c0ca2204c5cf7 to your computer and use it in GitHub Desktop.
Detecting leading spaces in a string using bash
#! /usr/bin/env bash
# This function will remove all spaces surrounding a string by
# using echo and IFS. Then it aggressively removes instances of
# the string from itself and everything that follows. In other words
# it returns a string that is the difference of itself with spaces
# and without spaces, specifically leading spaces. The length
# of the returned string is equal to the number of leading spaces.
# Not tested for tabs and other characters, but more fine-tuned
# use of IFS should allow for detection of those. It just wasn't
# necessary for my use.
# shellcheck disable=2116,2086,1083,2155,2046
function detect_leading_spaces {
# this is used by reading the return value using $?
# immediately after it is executed
# using a subshell to simplify handling IFS restoration
return $(
IFS=$' '
despaced=$( printf ${1} )
leading=$( IFS='' && eval printf \"\${1//${despaced}*}\" )
printf ${#leading}
)
}
# use like this:
detect_leading_spaces " test string " # test string has 2 leading spaces, 1 in the middle and 3 trailing spaces
# assign or use $?
echo $?
# $? must be used immediately after calling the function or the return value
# will be masked
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment