Skip to content

for loop (Example)

  • Run multiple bash scripts placed in templates folder
Bash
for f in templates/*.sh; do
  bash "$f"
done
  • Stop the execution when a script fails
Bash
for f in *.sh; do
  bash "$f" || break  # execute successfully or break
  # Or more explicitly: if this execution fails, then stop the `for`:
  # if ! bash "$f"; then break; fi
done
  • If you want to run x1.sh, x2.sh, ..., x10.sh
Bash
for i in `seq 1 10`; do
  bash "x$i.sh"
done
  • To preserve exit code of failed script
Bash
#!/bin/bash
set -e
for f in *.sh; do
  bash "$f"
done
  • Remove old files and keep last 3 (the latest)
Bash
#!/bin/bash
dirs=($(find /some/folder -type d))
for dir in "${dirs[@]}"; do
  cd "$dir"
  ls -pt | grep -v / | tail -n +4 | xargs rm -f
done
  • Combine for loop with sed to change text inside multiple files:
Bash
for i in $(find . -name values.yaml); do sed -i 's/docker1/docker2/g' $(find . -name values.yaml); done
Back to top