Script
This comprehensive guide covers shell scripting fundamentals and advanced techniques in Linux.
π Basic Script Structure
Script Basics
#!/bin/bash # Shebang - defines shell to use
# Script description here
# Author: Your Name
# Date: YYYY-MM-DD
# Variables
NAME="John"
AGE=25
# Main script content
echo "Hello, $NAME!"Running Scripts
# Make script executable
chmod +x script.sh
# Run script
./script.sh
bash script.sh
source script.sh # Run in current shellπ Variables and Data Types
Variable Declaration
# Basic variables
NAME="John" # String
AGE=25 # Integer
PRICE=99.99 # Float
readonly CONSTANT="value" # Constant
# Arrays
ARRAY=(item1 item2 item3)
echo "${ARRAY[0]}" # Access first element
echo "${ARRAY[@]}" # All elements
echo "${#ARRAY[@]}" # Array lengthSpecial Variables
$0 # Script name
$1-$9 # First 9 arguments
$# # Number of arguments
$@ # All arguments
$? # Last command exit status
$$ # Current process ID
$USER # Current username
$HOME # Home directory
$PWD # Current directoryπ Control Structures
Conditional Statements
# If statement
if [ "$a" -eq "$b" ]; then
echo "Equal"
elif [ "$a" -gt "$b" ]; then
echo "Greater"
else
echo "Less"
fi
# Case statement
case "$var" in
pattern1)
commands
;;
pattern2)
commands
;;
*)
default commands
;;
esacLoops
# For loop
for i in {1..5}; do
echo "$i"
done
# While loop
while [ "$count" -le 5 ]; do
echo "$count"
((count++))
done
# Until loop
until [ "$count" -gt 5 ]; do
echo "$count"
((count++))
doneπ Functions
Function Declaration
# Basic function
function_name() {
echo "Arguments: $@"
return 0
}
# Function with parameters
greet() {
local name="$1"
echo "Hello, $name!"
}
# Call functions
function_name arg1 arg2
greet "John"Function Libraries
# Source function library
source /path/to/library.sh
# Create library
lib_function() {
# Function code
}
# Export functions
export -f lib_functionπ₯ Input/Output
User Input
# Read input
read -p "Enter name: " name
read -s -p "Password: " pass # Silent input
read -n 1 -p "Continue? [Y/n]: " answer
# Select menu
select option in "Option 1" "Option 2" "Exit"; do
case $option in
"Exit")
break
;;
*)
echo "Selected: $option"
;;
esac
doneFile Operations
# Read file
while IFS= read -r line; do
echo "$line"
done < "input.txt"
# Write to file
echo "content" > file.txt # Overwrite
echo "content" >> file.txt # Appendπ οΈ String Operations
String Manipulation
# String length
string="Hello"
echo "${#string}"
# Substring
echo "${string:0:2}" # First 2 chars
echo "${string: -2}" # Last 2 chars
# Replace
echo "${string/l/L}" # First match
echo "${string//l/L}" # All matchesPattern Matching
# Remove pattern
echo "${string#pattern}" # From beginning
echo "${string%pattern}" # From end
# Case modification
echo "${string^^}" # To uppercase
echo "${string,,}" # To lowercaseπ’ Arithmetic Operations
Using expr
echo "Using expr"
expr 2 + 2
expr 2 - 2
expr 2 \* 2
expr 2 / 2
expr 2 % 2Using $(( ))
echo "Using $(( ))"
echo $((2 + 2))
echo $((2 - 2))
echo $((2 * 2))
echo $((2 / 2))
echo $((2 % 2))For float numbers use bc
bcecho "Using bc"
echo 4/3 | bc -l # bc is a calculatorArithmetic operations with variable
A=2
B=3
echo "Using variables"
echo $(( A + B ))
echo $(( A - B ))
echo $(( A * B ))
echo $(( A / B ))
echo $(( A % B ))Equals operators
[ "abc" = "abc" ]
If string1 is exactly equal to string2 - true
[ "abc" != "abc" ]
If string1 is equal to string2 - false
[ 5 -eq 5 ]
If integer1 is equal to integer2 - true
[ 5 -ne 5 ]
If integer1 is equal to integer2 - false
[ 6 -gt 5 ]
If integer1 is greater than integer2 - true
[ 6 -lt 5 ]
If integer1 is less than integer2 - false
[[ "abcd" = bc ]]
If abcd contains bc - true
[[ "abc" = ab[cd] ]]
If 3rd character of abc is c or d - true
[[ "abe" = ab[cd] ]]
If 3rd character of abc is c or d - false
[[ "abc" < "bcd" ]]
If "abc" comes after "bcd" when sorted in alphabetical order - true
[[ "abc" > "bcd" ]]
If "abc" comes after "bcd" when sorted in alphabetical order - false
Conditional operator
[[ A -gt 4 && A -lt 9 ]]
If A is greater than 4 and less than 9
[[ A -gt 4 || A -lt 9 ]]
If A is greater than 4 or less than 9
-e FILE
If FILE exists
-d FILE
If FILE is a directory
-s FILE
If FILE is not empty
-x FILE
If FILE is executable
-w FILE
If FILE is writable
Basic Math
# Arithmetic expansion
result=$((5 + 3))
((result++))
# bc for floating point
result=$(echo "scale=2; 5.75 + 3.25" | bc)
# expr for integers
result=$(expr 5 + 3)π Debugging
Debug Options
# Enable debugging
set -x # Print commands
set -e # Exit on error
set -u # Error on undefined variables
# Debug specific section
set -x
commands
set +xπ‘ Best Practices
Script Structure
Use meaningful variable names
Comment your code
Use functions for repeated code
Handle errors appropriately
Security
# Quote variables file_name="$1" # Check arguments if [ $# -lt 1 ]; then echo "Error: Missing arguments" exit 1 fi # Set secure permissions chmod 755 script.shError Handling
# Error function error() { echo "Error: $1" >&2 exit 1 } # Command error checking command || error "Command failed"
π Script Template
#!/bin/bash
#
# Script Name: script.sh
# Description: Brief description
# Author: Your Name
# Date: YYYY-MM-DD
# Exit on error
set -e
# Script variables
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"
# Functions
usage() {
cat << EOF
Usage: $SCRIPT_NAME [options]
Options:
-h, --help Show this help message
-v, --version Show version
EOF
}
# Main logic
main() {
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1"
usage
exit 1
;;
esac
shift
done
# Main script logic here
}
# Run main if script is not sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fiLast updated
Was this helpful?