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)