#!/bin/shell

# Length of a string/variable: ${#VAR}
# (Same operator for length of an array, but we have not studied that yet.)
MESSAGE="hello, world"
echo ${#MESSAGE}

# Substitutions: ${VAR:-STR}
# If VAR is not defined or null, the expansion of STR.
# Otherwise, the value of VAR.
FOO=foo
echo ${FOO:-"bar"}
echo ${XYZZY:-"bar"}
# Useful for setting a value for a variable if it has not been defined.

# Substitutions with replacement: ${VAR:=STR}
# As substitutions but STR is assigned VAR if it does not exist.
echo ${XYZZY:-"test"}
echo $XYZZY
echo ${XYZZY:="test"}
echo $XYZZY

# Test or exit: ${VAR:?STR}
# If VAR is not set, STR is printed in stdout and non-interactive shells
# quit.
echo ${IMPORTANT_VAR:?"This important var is not set, so bye!"}
echo "Important var is set so we can proceed"

# String slicing: ${VAR:OFFSET:LENGTH}
# Keeps LENGTH characters starting after OFFSET.
# If LENGTH is not provided, the remainder of the content is taken.
A_STRING="this is some string"
echo ${A_STRING:2}
echo ${A_STRING:0:5}
echo ${A_STRING::3}
echo ${A_STRING:(-1)}
echo ${A_STRING::(-1)}


# Replacing parts of a string: ${VAR/PATTERN/STRING}
# Replaces PATTERN by STRING in VAR.
NUMBERS="one, two, three, four, five"
echo $NUMBERS
echo ${NUMBERS/"three,"/"tres,"}

STR="hello, world"
echo ${STR^}
echo ${STR^^}

STR="HELLO, WORLD"
echo ${STR,}
echo ${STR,,}

# There are some other operators that we will not study.
# See the Bash man pages for more info.
# Example: obtaining prefixes and suffixes of a string:

file="/path/to/src/foo.c"

filename=${file##*/}
basepath=${file%$filename}

printf "Base path: %s\nFile name: %s\n" $basepath $filename
