-
-
Notifications
You must be signed in to change notification settings - Fork 2
Linux Bash Scripting Guide
Complete beginner-friendly guide to Bash scripting on Linux, covering Arch Linux, CachyOS, and other distributions including script creation, variables, loops, conditionals, and automation.
- Understanding Bash Scripting
- Creating Scripts
- Variables
- Conditionals
- Loops
- Functions
- Input/Output
- Troubleshooting
Bash scripting automates tasks using shell commands.
Uses:
- Automation: Automate repetitive tasks
- System administration: Manage systems
- File processing: Process files in bulk
- Backup scripts: Create automated backups
Benefits:
- Time saving: Automate manual tasks
- Consistency: Same tasks run the same way
- Error reduction: Fewer manual errors
Create script:
# Create script file
vim myscript.shAdd:
#!/bin/bash
echo "Hello, World!"Make executable:
# Make executable
chmod +x myscript.sh
# Run script
./myscript.shScript header:
#!/bin/bash
# This tells system to use bashSet variables:
#!/bin/bash
NAME="John"
AGE=25
echo "Name: $NAME"
echo "Age: $AGE"Use environment variables:
#!/bin/bash
echo "User: $USER"
echo "Home: $HOME"
echo "Path: $PATH"Store command output:
#!/bin/bash
DATE=$(date)
FILES=$(ls)
echo "Date: $DATE"
echo "Files: $FILES"Basic if:
#!/bin/bash
if [ "$1" == "hello" ]; then
echo "Hello!"
fiIf-else:
#!/bin/bash
if [ -f "$1" ]; then
echo "File exists"
else
echo "File not found"
fiCase:
#!/bin/bash
case "$1" in
start)
echo "Starting..."
;;
stop)
echo "Stopping..."
;;
*)
echo "Usage: $0 {start|stop}"
;;
esacFor loop:
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
doneLoop through files:
#!/bin/bash
for file in *.txt; do
echo "Processing: $file"
doneWhile loop:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
doneCreate function:
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "John"Return value:
#!/bin/bash
add() {
result=$(( $1 + $2 ))
echo $result
}
sum=$(add 5 3)
echo "Sum: $sum"Get user input:
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"Use arguments:
#!/bin/bash
echo "Script: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"Save output:
#!/bin/bash
# Redirect to file
echo "Hello" > output.txt
# Append to file
echo "World" >> output.txtCheck permissions:
# Make executable
chmod +x script.sh
# Check shebang
head -1 script.shDebug mode:
# Run with debug
bash -x script.sh
# Check syntax
bash -n script.shThis guide covered Bash scripting basics, variables, conditionals, loops, and functions for Arch Linux, CachyOS, and other distributions.
- Shell Configuration - Shell setup
- cron Guide - Schedule scripts
- systemd Timers Guide - Modern scheduling
-
Bash Documentation:
man bash
This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.