COMP7004 - Systems Scripting
Lecture 07: String Manipulations, Functions
Dr. Vincent Emeakaroha
vincent.emeakaroha@mtu.ie
Semester 2, 2026
String Manipulations
Bash supports a number of string manipulation operations.
${#string} gives the string length
${string:position} extracts sub-string from $string at $position
${string:position:length} extracts $length characters of sub-string from $string at $position
Can be used for arrays as we have seen previously.
Example
st=“ABCDEFGHIJ”
echo ${#st}
10
echo ${st:6}
GHIJ
echo ${st:5:2}
FG
String Case Conversion
String character case can be converted from upper to lower
case and verse versa using the command “tr”.
tr translates characters in its first argument to the
corresponding characters in its second argument. Example:
echo abcdefgh | tr ceh CEH # c => C, e => E, h => H
abCdEfgH
Ranges specified with a hyphen are expanded to include all
intervening characters. Example:
echo touchdown | tr ‘a-z’ A-Z’
TOUCHDOWN
Command Substitution
The backquote `” is different from the single quote “´. It is used
for command substitution: `command`
LIST=`ls`
echo $LIST
hello.sh read.sh
We can perform the command substitution by means of
$(command) -> more modern version
LIST=$(ls)
echo $LIST
hello.sh read.sh
Example
backup.sh
backup.sh
#!/bin/bash
BCKUP=/home/$USER/backup-$(date +%d-%m-%y).tar.gz
tar -czf $BCKUP projectFolderName
Will create an archive folder in a user home directory with
daily dates (e.g., backup-12-02-2026.tar.gz) to backup the
content of the folder named “projectFolderName
Bash Parameter Substitution 1
Used in manipulating or expanding variables
Very handy in providing missing command-line arguments
in scripts
${parameter-default}
If parameter is not set, use default
Another variant is ${parameter:-default}
Used only when parameter is declared but still has null value
Example:
param-sub1.sh
param-sub1.sh
#!/bin/bash
username0=
echo "username0 has been declared,
but is set to null."
echo "username0 = ${username0-`whoami`}"
echo
echo "username1 has not been declared."
echo "username1 = ${username1-`whoami`}"
username2=
echo "username2 has been declared,
but is set to null."
echo "username2 = ${username2:-`whoami`}"
Output:
username0 has been declared, but is set to null.
username0 =
username1 has not been declared.
username1 = Vincent
username2 has been declared, but is set to null.
username2 = vincent
Bash Parameter Substitution 2
${parameter=default}
If parameter is not set, set it to default
Another variant is ${parameter:=default}
Used only when parameter is declared but still has null value (as seen previously)
When a parameter is set
Parameter substitution has no effect (does not change value)
Example:
param-sub2.sh
Param-sub2.sh
#!/bin/bash
username=
echo "username has been declared, but is set to null."
echo "username = ${username=`whoami`}"
echo
echo "username1 has not been declared."
echo "username1 = ${username1=`whoami`}"
username2=
echo "username2 has been declared, but is set to null."
echo "username2 = ${username2:=`whoami`}"
username3=bill
echo "username3 has been assigned the value bill."
echo "username3 = ${username3=`whoami`}"
echo "Parameter substitution has no effect on set variable"
Output:
username has been declared, but is set to null.
username =
username1 has not been declared.
username1 = vincent
username2 has been declared, but is set to null.
username2 = Vincent
username3 has been assigned the value bill.
username3 = bill
Parameter substitution has no effect on set
variable
Shell Functions
A shell function is similar to a shell script
stores a series of commands for execution later
shell stores functions in memory
Functions can be called upon to execute its task when needed.
shell executes a shell function in the same shell that called it
Where to define
In .profile or .bashrc
In your script
Or on the command line
Remove a function
Use unset functionName
Functions: Syntax
Functions are declared as follows
function_name(){
List_of_commands
}
The name of the function is “function_name
Use to invoke the function anywhere in the script
Can be named anything
Function names should be descriptive of its actions
function.sh
#!/bin/bash
# Define your function here
Hello () {
echo "Hello Welcome to the World"
}
# Invoke your function
Hello
Functions: Passing Parameters
A Bash function can accept parameters during invocation
Unlike C-programming
Function parameters are not declared together with function name
Invalid: function_name(param1, param2,) {}
Function parameters are accessible inside functions as:
$1, $2, etc.
$# reflects number of parameters
$0 contains name of script (not name of function)
Example
function2.sh
function2.sh
#!/bin/bash
# Define your function here
Hello () {
echo "Hey $1 $2 Welcome to the World"
}
# Invoke your function
Hello Vincent Emeakaroha
Functions: Return Value
Functions can return value using the syntax
return value
Returned value mostly numerical. String (characters) is possible but complex
This command terminates the execution of the function
Returned value is stored in the shell variable $?” if not customised
Using the command “exitin a function
Terminates the function and the whole script
Bash return statement might not be really what you want
The only thing you can specify with return is the function’s own exit status
i.e., a value between 0 and 255, 0 meaning success.
Example
function3.sh
function3.sh
#!/bin/bash
# Define your function here
Hello () {
echo "Hey $1 $2 Welcome to the World"
return 20
}
# Invoke your function
Hello Vincent Emeakaroha
# Capture value returned by last command
ret=$?
echo "Return value is $ret"
Nested Functions
Functions can call
Itself in the case of recursive function
Another function
Example
Function4.sh
function4.sh
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}
number_two () {
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
Handling File
Whenever we run any command in shell, a new subshell or
process gets created, and the command runs in the newly
created process. When we run any argument to the exec
command, exec will replace the current shell with the
command to be executed. It does not create a new process
to run the command.
Every process has three files opened by default. These are
standard input, output and error. The file descriptor
associated with them are 0, 1 and 2 respectively.
In Bash shell, we can assign a file descriptor to any input or
output file using the exec command.
Opening and Closing File
The syntax for opening a file to write is
exec fd> filename
E.g., exec 3> content.txt
The syntax for opening a file to read is
exec fd< filename
E.g., exec 3< content.txt
The syntax for closing an open file is
exec fd<&- (input file) or exec fd>&- (output file)
E.g., exec 3<&- or exec 3>&-
In case of writing if “filename” does not exist, it will be created
automatically.
Opening, Writing and Closing File
#!/bin/bash
# Opening file for writting
exec 3> sample.txt
# writing simple text into the file with echo
echo "This is the first content to be written into our file" >&3
# run date command and store in the file
date >&3
# close the file
exec 3>&-
Output
This is the first content to be written into our file
Fri Feb 21 01:58:58 GMT 2025
Reading File
#!/bin/bash
# Opening file for reading purpose
exec 3< sampleInput.txt
# Read content and output to terminal
cat <&3
# close the file
exec 3<&-
NOTE:
Create the input file with some content before running the script
echo “How is it going?” > sampleInput.txt
Output
How is it going?
Bash Script Use Cases
Example usage scenarios
To put what we have learnt into action
Let us examine real world usages
...etc.
Change Filenames to Lower Case
(renamefile.sh)
Create a directory ”test” containing upper case file names before testing this code
#!/bin/bash
path=`pwd` # command substitution to get present working directory
for filename in $path/test/* # Traverse all files in directory.
do
fname=`basename $filename` #Extract the file names from the path
dname=`dirname $filename` #Extract the directory path
lowCaseName=`echo $fname | tr A-Z a-z` # translate upper characters to lower characters
if [ "$fname" != "$lowCaseName" ] # Rename only files not already lowercase.
then
upper=`echo "$dname/$fname"`
lower=`echo "$dname/$lowCaseName"`
mv $upper $lower # Rename file
fi
done
exit 0
File Comparison (compare.sh)
Files are compared byte by byte and not just the name
#!/bin/bash
ARGS=2 # Two args to script expected.
if [ $# -ne "$ARGS" ]; then
echo "Usage: `basename $0` file1 file2" ; exit 1
fi
if [[ ! -r "$1" || ! -r "$2" ]] ; then
echo "Both files must exist and be readable." ; exit 2
fi
cmp $1 $2 &> /dev/null # redirect the output of "cmp" command to /dev/null.
if [ $? -eq 0 ] # Test exit status of “cmp” command.
then
echo "File \"$1\" is identical to file \"$2\"."
else
echo "File \"$1\" differs from file \"$2\"."
fi
exit 0
Thank You!