Executable Shell Scripts (.sh) - A Comprehensive Guide
Basic Structure​
1. Create the Script File​
touch myscript.sh
2. Add Shebang Line​
The first line should specify the interpreter:
#!/bin/bash
Making Scripts Executable​
Method 1: Using chmod​
chmod +x myscript.sh
Method 2: Specific Permissions​
chmod 755 myscript.sh
Running Scripts​
Method 1: Direct Execution​
./myscript.sh
Method 2: Using bash​
bash myscript.sh
Script Writing Techniques​
Here Document (EOF) Example​
cat << 'EOF' > myscript.sh
#!/bin/bash
echo "Hello World"
echo "This is a multi-line script"
EOF
Basic Script Template​
#!/bin/bash
# Script description
# Author: Your Name
# Date: YYYY-MM-DD
# Variables
VARIABLE_NAME="value"
# Main logic
echo "Starting script..."
# Your commands here
echo "Script completed."
Best Practices​
- Always include shebang line
- Add comments for documentation
- Use meaningful variable names
- Include error handling
- Test for required dependencies
- Use proper file permissions
Common Permission Meanings​
755
: Owner can read/write/execute, others can read/execute700
: Only owner can read/write/execute644
: Owner can read/write, others can read600
: Only owner can read/write
Script Execution Troubleshooting​
If you encounter "Permission denied":
- Check file permissions
- Verify script location
- Ensure correct shebang
- Check file ownership
Example Script with Error Handling​
#!/bin/bash
# Exit on error
set -e
# Error handling function
handle_error() {
echo "Error occurred in script at line: $1"
exit 1
}
trap 'handle_error $LINENO' ERR
# Script logic here
echo "Script running..."