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
Special Variables
🔍 Control Structures
Conditional Statements
Loops
📊 Functions
Function Declaration
Function Libraries
📥 Input/Output
User Input
File Operations
🛠️ String Operations
String Manipulation
Pattern Matching
🔢 Arithmetic Operations
Using expr
Using $(( ))
For float numbers use bc
bcArithmetic operations with variable
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
🐛 Debugging
Debug Options
💡 Best Practices
Script Structure
Use meaningful variable names
Comment your code
Use functions for repeated code
Handle errors appropriately
Security
Error Handling
📋 Script Template
Last updated
Was this helpful?