Skip to content

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:

my_script.sh

Make the Script Executable

Before running the script, you must make it executable:

chmod +x my_script.sh

Running the Script

You can now run your script in one of the following ways:

1. From the current directory:

./my_script.sh

2. With the full path:

~/my-scratch/scripts/my_script.sh

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):

export PATH=$PATH:$HOME/my-scratch/scripts

Permanently (every time you open a terminal):

  1. Open your .bashrc file:
nano ~/.bashrc
  1. Add the following line at the bottom:
export PATH=$PATH:$HOME/my-scratch/scripts
  1. Reload .bashrc:
source ~/.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:

^M: command not found

To fix this, convert the file with:

dos2unix my_script.sh

This will replace the line endings with Linux-compatible ones.


Best Practices

  • ✅ Use .sh as the file extension (e.g., backup.sh, run_analysis.sh)
  • ✅ Start scripts with a shebang: #!/bin/bash
  • ✅ Add descriptive comments using #
  • ✅ Use set -e at 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:

./greet.sh Alice

Output:

Hello, Alice! Welcome to the Linux command line.

External Resources