for loop (Example)
- Run multiple bash scripts placed in templates folder
- 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
- To preserve exit code of failed script
- 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
Examples
- example 1
Bash
#!/bin/bash
# Path to the folder containing images
image_folder="work"
# Path to the output folder
output_folder="output"
# Create output folder if it doesn't exist
mkdir -p "$output_folder"
# Counter for keeping track of the current line in date-list.txt
counter=1
# Iterate over each image file in the work folder
for image_file in "$image_folder"/*.jpg; do
# Read the corresponding line from date-list.txt
timestamp=$(sed -n "${counter}p" date-list.txt)
# Check if timestamp is empty or date-list.txt is exhausted
if [ -z "$timestamp" ]; then
echo "No more timestamps available from date-list.txt"
break
fi
# Copy image to output folder with timestamp as filename
cp "$image_file" "$output_folder/${timestamp}.jpg"
echo "Copied $image_file to $output_folder/${timestamp}.jpg"
# Increment counter for next timestamp
((counter++))
done