Linux shell script Tips
Mastering Linux shell script
Command | Effect |
---|---|
#!/bin/bash | Specifies bash as the interpreter for the script |
Command | Effect |
---|---|
myVar=”value” | Assigns the value to the variable myVar |
${myVar} | Access the value of myVar |
unset myVar | Unsets the variable myVar |
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 |
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 |
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 |
Command | Effect |
---|---|
myFunction() { commands; } | Defines a function named myFunction with the given commands |
myFunction “arg1” “arg2” | Calls the function myFunction with arguments |
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 |
Command | Effect |
---|---|
# Single line comment | Comments out the rest of the line |
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 |
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 |
Command | Effect |
---|---|
$1, $2, $3, … | Access the first, second, third, etc., command-line arguments |
$# | Number of command-line arguments passed |
$@ | All command-line arguments |
a 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 |
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 |
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 |
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 |
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 |
Table of Contents
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!