Skip to content

Shell Scripting

PotatoScript edited this page Mar 30, 2025 · 1 revision

Shell Scripting Basics

πŸ“œ 1. Introduction to Shell Scripting

A shell script is a text file containing a series of commands that are executed by the shell, which is a command-line interface (CLI) in Linux. Shell scripts allow you to automate repetitive tasks, manage system operations, and enhance the power of the shell environment.

πŸ§‘β€πŸ’» What Is a Shell?

The shell is a program that takes commands from the user and executes them. Common shells include:

  • Bash (Bourne Again Shell): The most common and widely used shell in Linux.
  • Zsh: A feature-rich shell with additional capabilities.
  • Fish: A user-friendly shell with intuitive features.

✍️ 2. Writing Your First Shell Script

A basic shell script can be as simple as running a few commands, and it can be made executable to automate tasks.

πŸ“ Step-by-Step Guide:

  1. Create a new file: Use your favorite text editor (e.g., nano, vim) to create a new script file. For example, let's create a file named hello_world.sh.

    nano hello_world.sh
  2. Add the shebang line: The first line of your script should be a special comment called a "shebang" (#!/). This line tells the system which shell to use to execute the script.

    #!/bin/bash
  3. Add your script content: After the shebang line, add commands you want to execute. For example:

    #!/bin/bash
    echo "Hello, World!"
  4. Save and exit: Save the file and exit the editor. If using nano, press CTRL+O, then ENTER, and CTRL+X to exit.

  5. Make the script executable: You need to give the script executable permissions.

    chmod +x hello_world.sh
  6. Run the script: Finally, you can execute your script by running it with ./.

    ./hello_world.sh

    Output:

    Hello, World!

πŸ”„ 3. Variables in Shell Scripting

In shell scripts, you can store values in variables and use them throughout the script.

πŸ§‘β€πŸ’» Defining Variables:

To define a variable, just type the variable name followed by = and the value (no spaces around the = sign).

name="Lucy"
echo "Hello, $name!"

This will output:

Hello, Lucy!

πŸ§‘β€πŸ’» Common Variables:

  • $USER: The username of the currently logged-in user.
  • $HOME: The home directory of the current user.
  • $PWD: The current working directory.

🎯 4. Control Structures in Shell Scripting

Control structures such as if statements, loops, and case statements help you control the flow of execution in your shell script.

πŸ§‘β€πŸ’» If Statements:

If statements allow you to run code based on conditions.

Example:

#!/bin/bash
if [ $1 -gt 10 ]; then
  echo "The number is greater than 10."
else
  echo "The number is less than or equal to 10."
fi

Explanation:

  • $1 refers to the first command-line argument.
  • -gt checks if the number is greater than 10.

To run the script with a number argument:

./number_check.sh 15

Output:

The number is greater than 10.

πŸ§‘β€πŸ’» For Loops:

For loops are used for repetitive tasks.

Example:

#!/bin/bash
for i in {1..5}
do
  echo "Loop iteration $i"
done

Output:

Loop iteration 1
Loop iteration 2
Loop iteration 3
Loop iteration 4
Loop iteration 5

πŸ§‘β€πŸ’» While Loops:

While loops continue as long as a condition is true.

Example:

#!/bin/bash
count=1
while [ $count -le 5 ]
do
  echo "Count is $count"
  ((count++))
done

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

🧩 5. Functions in Shell Scripting

Functions allow you to organize your code into reusable blocks. You can define functions and call them when needed.

πŸ§‘β€πŸ’» Defining Functions:

#!/bin/bash
function greet {
  echo "Hello, $1!"
}

greet "Lucy"

Output:

Hello, Lucy!

⏳ 6. Command-Line Arguments

Shell scripts can accept arguments that are passed when the script is executed. These arguments are stored in special variables like $1, $2, etc.

πŸ§‘β€πŸ’» Using Command-Line Arguments:

#!/bin/bash
echo "The first argument is: $1"
echo "The second argument is: $2"

Run the script like this:

./args_script.sh Hello World

Output:

The first argument is: Hello
The second argument is: World

🧹 7. Redirecting Output

You can redirect the output of your commands to files or other locations using > and >>.

πŸ§‘β€πŸ’» Redirecting Output:

  • > overwrites the file.
  • >> appends to the file.

Example:

#!/bin/bash
echo "This is a test" > output.txt

This will overwrite the contents of output.txt with "This is a test".

To append:

echo "Appending text" >> output.txt

πŸ› οΈ 8. Debugging Shell Scripts

Debugging shell scripts is crucial when things don’t go as expected. You can use the -x option to print each command and its arguments as they are executed.

πŸ§‘β€πŸ’» Enable Debugging:

#!/bin/bash
set -x
echo "This will print each command."

🧰 9. Working with Files and Directories

Shell scripts can interact with the file system, such as creating files, directories, or checking if they exist.

πŸ§‘β€πŸ’» File Operations:

  • Create a file: touch filename

  • Create a directory: mkdir directory_name

  • Check if a file exists:

    if [ -f "myfile.txt" ]; then
      echo "File exists"
    else
      echo "File does not exist"
    fi

⚠️ 10. Error Handling in Shell Scripting

It's important to handle errors in your shell scripts to avoid unexpected behavior. You can use exit codes to indicate success or failure.

πŸ§‘β€πŸ’» Exit Status:

  • 0 means success.
  • Non-zero values indicate errors.

Example:

#!/bin/bash
if [ ! -f "myfile.txt" ]; then
  echo "Error: File not found!"
  exit 1
else
  echo "File found!"
fi

Clone this wiki locally