Shell Scripting
Shell scripting is a powerful way to automate repetitive tasks, run sequences of commands, and manage complex workflows in Linux environments — especially useful in High Performance Computing (HPC), system administration, and development.
Why Shell Scripts?
Instead of manually typing commands one by one, you can write them into a file (called a script) and execute the file. This saves time, reduces mistakes, and enables reproducibility.
Creating a Shell Script
Start by creating a simple text file using a plain text editor like nano, vim, or Visual Studio Code.
Example script:
#!/bin/bash
# my_script.sh - A basic example script
# Print the current date
echo "Today's date is:"
date
# Show the current user
echo "You are logged in as: $USER"
# List files in the current directory
echo "Listing files in the current directory:"
ls -lh
# Print system uptime
echo "System uptime:"
uptime
Save the file as:
Make the Script Executable
Before running the script, you must make it executable:
Running the Script
You can now run your script in one of the following ways:
1. From the current directory:
2. With the full path:
Making Scripts Globally Available
To be able to run your script from any location in the terminal, add the folder where it’s stored to your system PATH.
Temporarily (for current session):
Permanently (every time you open a terminal):
- Open your
.bashrcfile:
- Add the following line at the bottom:
- Reload
.bashrc:
Important Notes
Windows vs. Linux Line Endings
Scripts created in Windows may contain CRLF line endings instead of the Unix standard LF. This can result in errors such as:
To fix this, convert the file with:
This will replace the line endings with Linux-compatible ones.
Best Practices
- ✅ Use
.shas the file extension (e.g.,backup.sh,run_analysis.sh) - ✅ Start scripts with a shebang:
#!/bin/bash - ✅ Add descriptive comments using
# - ✅ Use
set -eat the top to stop on errors - ✅ Use
"$@"to safely handle input arguments - ✅ Use indentation and consistent formatting
Example: Script with Arguments
You can make your script more interactive by accepting parameters. For example:
#!/bin/bash
# greet.sh - Greets the name passed as an argument
if [ $# -eq 0 ]; then
echo "Usage: ./greet.sh <name>"
exit 1
fi
echo "Hello, $1! Welcome to the Linux command line."
Run it:
Output: