DEV Community

tamilvanan
tamilvanan

Posted on

Shell scripting -001

Note: Iโ€™m not an expert. Iโ€™m writing this blog just to document my learning journey. ๐Ÿš€


๐Ÿง  What is a Shell Script?

A shell script is a text file containing a sequence of shell commands that are executed one after another, as if you were typing them into a terminal.

It uses a shell (like bash, sh, or zsh) as the program that interprets and runs the commands.


๐Ÿงฉ Key Concepts

๐Ÿ”น 1. Shell = Command-Line Interpreter

The shell is a program that takes user input and executes commands.

  • Example shells: bash, zsh, fish, dash, sh
  • They understand commands like cd, ls, echo, cp, etc.
  • Shells can also run scripts โ€” a file with a list of commands.

๐Ÿ”น 2. Shell Script = Text File of Commands

A shell script is just a plain text file with:

  • A shebang (#!)
  • A list of commands
  • Optional logic (if, loops, functions)
#!/bin/bash
echo "Hello, world!"
Enter fullscreen mode Exit fullscreen mode
  • The first line (#!/bin/bash) tells the system to use the bash shell to interpret the file.
  • Each line is executed top to bottom, like typing into the terminal.

๐Ÿ”น 3. Variables, Conditions, and Loops

Shell scripts become powerful because they support programming logic:

๐Ÿ“ฆ Variables:

name="Computer"
echo "Hello, $name"
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Loops:

for file in *.txt; do
  echo "Processing $file"
done
Enter fullscreen mode Exit fullscreen mode

โ“ Conditionals:

if [ "$name" = "Computer" ]; then
  echo "Welcome back!"
fi
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น 4. Exit Codes and Errors

Every command returns an exit code:

  • 0 = success
  • non-zero = error

You can check:

if [ $? -ne 0 ]; then
  echo "The last command failed!"
fi
Enter fullscreen mode Exit fullscreen mode

Or use set -e to make the script stop on any error.


๐Ÿ”น 5. Execution

Make the script executable:

chmod +x myscript.sh
./myscript.sh
Enter fullscreen mode Exit fullscreen mode

Or run it like:

bash myscript.sh
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Final Definition

A shell script is a plain text file that contains a structured sequence of commands written for a shell interpreter. It allows automation of tasks by combining built-in shell functionality (variables, conditionals, loops) with standard system commands. The script is executed line-by-line, and each commandโ€™s success or failure affects the flow of execution.


Top comments (0)