Fundamental Shell Scripting Concepts
Variables and Parameters
In shell scripts, you can define and use variables to store and manipulate data. Variables are assigned values using the =
operator, and their values can be accessed using the $
prefix. For example:
name="LabEx"
echo "Hello, $name!"
You can also pass parameters to a shell script when you run it, and access them using the $1
, $2
, etc. variables.
Conditional Statements
Shell scripts support conditional statements, such as if-else
and case
, to make decisions based on certain conditions. For example:
if [ "$1" == "start" ]; then
echo "Starting the service..."
else
echo "Usage: $0 start"
fi
Loops
Shell scripts can use loops, such as for
, while
, and until
, to execute a block of code multiple times. For example:
for i in 1 2 3 4 5; do
echo "Iteration $i"
done
Functions
You can define and call your own functions in shell scripts to encapsulate and reuse code. Functions are defined using the function
keyword or the ()
syntax, and can accept parameters and return values.
function greet() {
echo "Hello, $1!"
}
greet "LabEx"
Exit Codes and Error Handling
Shell scripts use exit codes to indicate the success or failure of a command or the script as a whole. You can use the $?
variable to check the exit code of the last command, and handle errors using conditional statements.
./my_script.sh
if [ $? -ne 0 ]; then
echo "An error occurred. Exiting..."
exit 1
fi
Understanding these fundamental concepts will help you write more robust and effective shell scripts.