Shell Scripting

Overview

  • Time: 30 min

  1. Learn about shell scripts and how to create them.

  2. Learn the differences between source and sh commands.

A shell script is a file containing a series of commands that can be executed in the terminal. You can create a shell script to automate the creation of your directories and environment variables.

1 cd  /scratch/$PROJECT/$USER/hpc101
2 ls
3 cd session1
4 cat env.sh

You can run the shell script using the following command:

1sh env.sh

or

1source env.sh

or

1. env.sh
Comparison between source and sh

Feature

source (or .)

sh

Shell Environment

Runs script in the current shell

Runs script in a new sub-shell

Persistence

Changes (e.g., variables, cd) persist

Changes do not persist after exit

Typical Use

Load config files, environment variables, functions

Run standalone shell scripts

Syntax

source script.sh or . script.sh

sh script.sh

Shebang Ignored?

Yes

No — uses shebang or defaults to sh

Performance

Slightly faster (no new process)

Slower (spawns a new shell process)

Key Points

  • A shell script is a file containing a series of commands that can be executed in the terminal.

  • You can run the shell script using the sh, source, or . commands.