_strlen() { #print the length of a string, return 1 on failure
[ -z "${1}" ] && return 1
printf "%s\\n" "${#1}"
}
#==================================================== Example ====
#_strlen "hello world!" #returns "12"
#=================================================================
READ A FILE INTO ARRAY
You can use a loop to read each line of your file and put it into the array
# Read the file in parameter and fill the array named "array"
getArray() {
array=() # Create array
while IFS= read -r line # Read a line
do
array+=("$line") # Append line to the array
done < "$1"
}
getArray "file.txt"
How to use your array :
# Print the file (print each element of the array)
getArray "file.txt"
for e in "${array[@]}"
do
echo "$e"
done
function get_script_dir () {
# Capture script directory (Full)
# Resolve if its symlink
# Call as : echo "$(get_script_dir)"
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$( readlink "$SOURCE" )"
# If $SOURCE was a relative symlink (so no "/" as prefix, need to resolve it relative to the symlink base directory
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
echo "$DIR"
}
# Convert to uppercase
function toupper(){
# Converts string(s) passed as argument(s)
#+ to uppercase
if [ -z "$1" ] # If no argument(s) passed,
then #+ send error message
echo "(null)" #+ (C-style void-pointer error message)
return #+ and return from function.
fi
echo "$@" | tr a-z A-Z
# Translate all passed arguments ($@).
return
# Use command substitution to set a variable to function output.
# For example:
# oldvar="A seT of miXed-caSe LEtTerS"
# newvar=`tolower "$oldvar"`
# echo "$newvar" # a set of mixed-case letters
#
}
counter=$2
case $1 in
-f) factorial=1
while [ $counter -gt 0 ]
do
factorial=$(($factorial * $counter))
counter=$(( $counter - 1 ))
done
echo "The factorial is $factorial"
;;
-a) sumofparts=0
while [ $counter -gt 0 ]
do
sumofparts=$(($sumofparts + $counter))
counter=$(( $counter - 1 ))
done
echo "The sumofparts is $sumofparts"
;;
esac
function chk_args()
{
# Checks number of arguments
# Call as chk_args $#
local nbr_args=$1
if [ $nbr_args -ne $ARGS_NBR ]; then
echo "Wrong number of parameters = " $nbr_args
echo "Usage: " $this_job " <parm_srch_str> <parm_file_out>"
exit 69
else
# Print a /correct/ message and continue
echo "Correct number of paramaters = $ARGS_NBR supplied "
echo "Proceeding..."; echo
# In case we need to assign parameters to variables
# Call as chk_Args $# $1 $2
# parm_srch_str=$2
# parm_file_out=$3
return 0
fi
}
function chk_abnd()
{
local abnd
abnd=$1
date
if [ $abnd -ne 0 ]; then
echo "Failed with status " $abnd; echo
#rm +++++++++++++
exit $abnd
#return $abnd
else
echo "Done"; echo
fi
}