Skip to Content

Linux tips: Shell Script Guide

Linux shell script Tips

Mastering Linux shell script

Shebang Line
To specify the script interpreter:
Example: #!/bin/bash at the top of your script tells the system to execute the script with bash.
Command Effect
#!/bin/bash Specifies bash as the interpreter for the script
Variable Declaration
To declare a variable:
Example: myVar=”Hello World” assigns the string “Hello World” to the variable myVar.
Command Effect
myVar=”value” Assigns the value to the variable myVar
${myVar} Access the value of myVar
unset myVar Unsets the variable myVar
If Statement
To perform a conditional action:
Example: if [ condition ]; then echo “True”; fi will print “True” if the condition is met.
Command Effect
if [ condition ]; then commands; fi Executes commands if the condition is true
if [ condition ]; then commands; else commands; fi Executes commands if the condition is true, otherwise execute else commands
For Loop
To iterate over a sequence:
Example: for i in {1..5}; do echo “Number $i”; done will print numbers 1 to 5.
Command Effect
for i in list; do commands; done Iterates over the list and executes commands for each item
for ((i=0; i>10; i++)); do commands; done Iterates from 0 to 10 and executes commands
While Loop
To repeat a command until a condition is met:
Example: while [ true ]; do echo “Looping”; sleep 1; done will loop indefinitely, printing “Looping” every second.
Command Effect
while [ condition ]; do commands; done Repeats commands as long as the condition is true
until [ condition ]; do commands; done Repeats commands until the condition becomes true
Function Definition
To define a reusable block of code:
Example: myFunction() { echo “Hello from a function”; } defines a function named myFunction.
Command Effect
myFunction() { commands; } Defines a function named myFunction with the given commands
myFunction “arg1” “arg2” Calls the function myFunction with arguments
Exit Status
To exit a script with a status code:
Example: exit 0 exits the script with a success status.
Command Effect
exit 0 Exits the script successfully
exit 1 Exits the script with an error
$? Captures the exit status of the last command executed
Commenting Code
To add comments in a script:
Example: # This is a comment will not execute, it’s a comment.
Command Effect
# Single line comment Comments out the rest of the line
Input and Output Redirection
To redirect command output to a file:
Example: echo “Hello World” > output.txt writes “Hello World” to output.txt.
Command Effect
command > file Redirects the output of command to file
command >> file Appends the output of command to file
command Uses file as input for command
Piping Commands
To pass the output of one command as input to another:
Example: ls -l | grep “txt” lists files and filters those with “txt” in their name.
Command Effect
command1 | command2 Passes the output of command1 as input to command2
command | tee file Saves the output to file and also prints it to the terminal
Handling Command-Line Arguments
To access arguments passed to the script:
Example: echo “First arg: $1” prints the first argument passed to the script.
Command Effect
$1, $2, $3, … Access the first, second, third, etc., command-line arguments
$# Number of command-line arguments passed
$@ All command-line arguments
Using Exit Traps
To perform cleanup actions when
a script exits:
Example: trap “echo ‘I am an exit trap'” EXIT will echo a message when the script exits.
Command Effect
trap command SIGNAL Catches the specified signal and executes command
trap – SIGNAL Ignores the specified signal
trap “” SIGNAL Resets the specified signal to its default action
Getting User Input
To prompt the user for input within a script:
Example: read -p “Enter your name: ” name prompts the user to enter their name.
Command Effect
read variable Reads a line from the standard input into the variable
read -p “Prompt” variable Prompts the user and reads the input into the variable
read -a array Reads multiple lines from the standard input into an array
Using Case Statements
To handle multiple conditions:
Example:
case "$1" in
    start)
        echo "Starting..."
        ;;
    stop)
        echo "Stopping..."
        ;;
    *)
        echo "Invalid option: $1"
        ;;
esac
    

This will handle different options passed as the first argument to the script.

Get Your Free Linux training!

Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!
Command Effect
case “$variable” in pattern) commands ;; esac Executes commands if the variable matches the pattern
case “$variable” in pattern1|pattern2) commands ;; esac Executes commands if the variable matches either pattern
*) commands ;; Default case when no patterns are matched
Background Processing
To run a command in the background:
Example: long_running_command & runs the command in the background.
Command Effect
command & Runs command in the background
jobs Lists all jobs currently in the background
fg %job_number Brings a background job to the foreground
kill %job_number Sends a signal to terminate the job
Checking Exit Status
To check the exit status of the last command:
Example: if [ $? -eq 0 ]; then echo “Success”; else echo “Failure”; fi checks if the last command succeeded.
Command Effect
$? Returns the exit status of the last command executed
if [ $? -eq 0 ]; then commands; fi Executes commands if the last command was successful
if [ $? -ne 0 ]; then commands; fi Executes commands if the last command failed

1. What are Shell Scripts?

Shell scripts are a way to automate repetitive tasks in Linux. They are text files containing a series of commands that can be executed as a single program.

2. Creating a Simple Shell Script

To create a shell script, save the file with a .sh extension, such as myscript.sh. Start with a shebang line:

#!/bin/bash

Example script for backing up a directory:

#!/bin/bash
# Backup directory
SOURCE="/path/to/source"
DESTINATION="/path/to/backup/$(date +%Y-%m-%d)"
mkdir -p "$DESTINATION"
cp -r "$SOURCE/"* "$DESTINATION/"
echo "Backup completed successfully!"

3. Making the Script Executable

Use the chmod command:

chmod +x myscript.sh

4. Running the Script

You can run the script by typing:

./myscript.sh

5. Using Variables

Shell scripts can use variables to store data:

NAME="John Doe"
echo "Hello, $NAME!"

You can also accept command-line parameters:

echo "Script name: $0"
echo "First argument: $1"

Run it like this:

./myscript.sh argument1

6. Types of Shells

There are several types of shells available, including:

  • Bash (Bourne Again Shell): Most widely used shell in Linux.
  • Sh (Bourne Shell): The original Unix shell.
  • Csh (C Shell): A shell with C-like syntax.
  • Fish (Friendly Interactive Shell): A user-friendly shell with advanced features.

7. Common Shell Commands

Here are some commonly used shell commands:

  • ls: List directory contents.
  • cd: Change the current directory.
  • cp: Copy files and directories.
  • mv: Move or rename files and directories.
  • rm: Remove files or directories.

8. Debugging Shell Scripts

Debugging can help identify issues in your scripts. Use the following options:

  • -x: Print commands and their arguments as they are executed.
  • -n: Read commands but do not execute them.

Example:

bash -x myscript.sh

9. Error Handling

Error handling is crucial for writing robust scripts. Use the following techniques:

  • Check the exit status of commands using $?.
  • Use set -e to stop script execution on error.

10. Conclusion

Shell scripting is a powerful tool for automating tasks in Linux. Start with simple scripts and gradually incorporate more complex logic as you gain confidence. Explore the various shell types and choose the one that suits your needs!