📌 Basics
- Start scripts with
#!/bin/bash(called shebang) #is used for single-line comments- Multi-line comments can be done using
: ' comment block ' echo "Hello"- print outputread name- take user input- Command substitution:
$(command)or backticks`command`
📦 Variables
name="Pradeep"- create variableecho $name- access variable- Special variables:
$0- script name$1 $2 ...- command-line arguments$#- number of arguments$@- all arguments$?- exit code of last command$$- current script PID
⚖️ Conditions
if [ condition ]; then ... fiif ... elif ... else ... ficase $var in pattern) ... ;; esac- Common tests:
-f file- file exists-d dir- directory exists-e file- file exists (any type)-s file- file not empty-r/-w/-x file- readable/writable/executable-eq/-ne/-gt/-lt/-ge/-le- integer comparisons=/!=- string comparison
🔁 Loops
for i in 1 2 3; do ... donewhile [ condition ]; do ... doneuntil [ condition ]; do ... donebreakandcontinueto control loops
🧩 Functions
-
function greet() { echo "Hello $1" } greet "Pradeep" - Use
returnto send exit codes (0=success)
📚 Arrays
arr=(one two three)echo ${arr[0]}- first elementecho ${arr[@]}- all elementsfor i in "${arr[@]}"; do echo $i; done
⚡ String Operations
${#str}- length${str:0:5}- substring${str/old/new}- replace text
🚨 Error Handling
- Check exit code:
if [ $? -ne 0 ]; then echo "failed"; fi - Stop on error:
set -e - Debug mode:
set -x(shows commands as they run) - Use
trapto catch errors and cleanup
📝 Input/Output & Redirection
command > file- redirect outputcommand >> file- append outputcommand < file- input from filecommand 2> errors.txt- redirect errors- Pipes:
cmd1 | cmd2
⏳ Date and Time
date +"%Y-%m-%d %H:%M:%S"- current date and time$(date +%s)- current timestamp
📌 Best Practices
- Always quote variables:
"$var"to prevent word splitting - Add comments for readability
- Use meaningful variable and function names
- Keep scripts executable with
chmod +x script.sh
💡 Example Script
#!/bin/bash
read -p "Enter filename: " file
if [ -f "$file" ]; then
echo "Content of $file:"
cat "$file"
else
echo "File not found"
fi