Loops in Bash – Master for and while for Automation & Batch Processing!
Need to repeat commands or process multiple files efficiently? In this video, we'll show you how to use loops in Bash to automate repetitive tasks. Whether you're renaming files, pinging servers, or processing logs, for and while loops are essential tools for every Linux user and scripter. Simple, powerful, and built into every shell! Learn: ✅ Step-by-Step Guide: 1.For Loop – Loop Over a List: for name in alice adam amir; do echo "Hello $name" done 2.For Loop – Loop Over Numbers: for i in 1 2 3 4 5; do echo "Number: $i" done # Shorter range syntax: for i in {1..10}; do echo $i done 3.For Loop – Process Files: for file in *.txt; do echo "Processing $file" done 4.While Loop – Counter Example: count=1 while [ $count -le 5 ]; do echo "Count: $count" ((count++)) done 5.While Loop – Read File Line by Line: while read line; do echo "Line: $line" done 〈 file.txt 6.Real-World Examples: # Rename all .jpg to .backup.jpg for file in *.jpg; do mv "$file" "${file%.jpg}.backup.jpg" done # Create 5 numbered folders for i in {1..5}; do mkdir "folder_$i" done # Ping multiple servers for server in google.com gitlab.com; do ping -c 1 $server && echo "$server is up" done 7.One-Liners for Quick Tasks: for i in 1 2 3; do echo $i; done for file in *.txt; do wc -l "$file"; done ✅ Why Use Loops in Bash? Automation: Repeat commands without manual typing. Batch Processing: Handle multiple files or inputs efficiently. Scripting Foundation: Essential for building robust shell scripts. Universal: Works in Bash, Sh, Zsh, and all POSIX shells. ✅ Pro Tips: Always quote variables in loops: "$file" to handle spaces in filenames. Use ${file%.jpg} for parameter expansion to strip extensions cleanly. Combine loops with conditionals: if [ -f "$file" ]; then ... for safety. Test loops with echo first before running destructive commands like mv or rm. Use seq for dynamic ranges: for i in $(seq 1 100); do ... You can find the full tutorial here: 📁 https://gitlab.com/hatem-badawi/linuxhowto/-/tree/main/bash/bash-loops Perfect for Linux users who want to automate tasks and write efficient Bash scripts! Hit subscribe for more command-line tips and like if this helped. Let us know: What's your most useful Bash loop? 👉 Watch now and master automation with Bash loops! #LinuxTips #BashScripting #CommandLine #Automation #ForLoop #WhileLoop #SysAdmin (Short, clear, and packed with practical knowledge!)
Download
0 formatsNo download links available.