Please enable JavaScript eh!

 ⌘ Web Mechanic ⌘ 

Bash Scripting


Functions 103

A few more string functions to fill up your toolbox.

trunc

When you need to make sure a string is only a certain number of characters long, you might need to truncate it.

trunc() {
    local str="$1"
    local len="$2"
    if [ "${#str}" -gt "$len" ]; then
        echo "${str:0:$len}"
    else
        echo "$str"
    fi
}
Usage:
myLongstr="primis a fringilla erat maximus "
HowLong=17
myShortstr=$(trunc "$myLongstr" 17)
echo "\$myLongstr : -->$myLongstr<--"
echo "\$myShortstr: '-->$myShortstr'<--"
$myLongstr : -->primis a fringilla erat maximus <--
$myShortstr: -->primis a fringill<--br/>

Note that this removes (truncates) from the END of the string.

upcase

Convert a string all upper-case

uppercase() {
    echo "$1" | tr '[:lower:]' '[:upper:]'
}
Usage:
myStr="The use of double quotation marks will help eliminate unnecessary word wrapping, word splitting, and whitespace when variable values contain a separator character or whitespace."
myStrUp=$(uppercase "$myStr")
echo "\$myStrUp: $myStrUp"

$myStr  : The use of double quotation marks will help eliminate unnecessary word wrapping, word splitting, and whitespace when variable values contain a separator character or whitespace.
$myStrUp: THE USE OF DOUBLE QUOTATION MARKS WILL HELP ELIMINATE UNNECESSARY WORD WRAPPING, WORD SPLITTING, AND WHITESPACE WHEN VARIABLE VALUES CONTAIN A SEPARATOR CHARACTER OR WHITESPACE.

Of course we also might need the opposite ...

lowercase

lowercase() {
    echo "$1" | tr '[:upper:]' '[:lower:]'
}
Usage:
myStrUp: THE USE OF DOUBLE QUOTATION MARKS WILL HELP ELIMINATE UNNECESSARY WORD WRAPPING, WORD SPLITTING, AND WHITESPACE WHEN VARIABLE VALUES CONTAIN A SEPARATOR CHARACTER OR WHITESPACE.
myStrLow=$(lowercase "$myStrUp") echo "\$myStrUp: $myStrUp" echo "\$myStrLow: $myStrLow"

 $myStrUp: THE USE OF DOUBLE QUOTATION MARKS WILL HELP ELIMINATE UNNECESSARY WORD WRAPPING, WORD SPLITTING, AND WHITESPACE WHEN VARIABLE VALUES CONTAIN A SEPARATOR CHARACTER OR WHITESPACE.
$myStrLow: the use of double quotation marks will help eliminate unnecessary word wrapping, word splitting, and whitespace when variable values contain a separator character or whitespace.

In these past few function pages, we've used a few new commands (awk, sed, tr, grep).

Use the resources link to find out more about them.

We also introduced some funky regular expression classes so we should explain more about that.

Regex Classes