Loop over files (Bash): verschil tussen versies
Naar navigatie springen
Naar zoeken springen
Regel 3: | Regel 3: | ||
== Examples == | == Examples == | ||
− | Start simple | + | === Start simple === |
<pre> | <pre> | ||
Regel 14: | Regel 14: | ||
done | done | ||
</pre> | </pre> | ||
+ | |||
+ | === Operate on each file === | ||
Create links to all files in this folder, and put those links in another folder: | Create links to all files in this folder, and put those links in another folder: |
Versie van 8 aug 2022 10:07
This is cool: You can loop over files in a directory and do stuff with it!
Examples
Start simple
#!/bin/bash cd ~/images-tmp for file in * do echo "File name: $file" done
Operate on each file
Create links to all files in this folder, and put those links in another folder:
for file in *.jpg do source="${PWD}/${file}" link="/var/www/media.example.com/tmp2/$file" echo " Path+file: $source - Destination: $link" ln -s "$source" "$link" done
Including shopt
I've seen the shopt
statements in examples from others. Turned out I really need them. And yes: This is not the most elegant or efficient script. It works.
################################################################################ # create_all_links_from_directory() ################################################################################ # create_all_links_from_directory() { # # First loop for .jpg # for file in *.jpg do source="${PWD}/${file}" link="${root}all-product-images/$file" echo " Source: $source Link: $link" ln -s "$source" "$link" done # Second loop for .png # for file in *.png do source="${PWD}/${file}" link="${root}all-product-images/$file" echo " Source: $source Link: $link" ln -s "$source" "$link" done } ################################################################################ # Loop through directories ################################################################################ # # From most to least relevant? ######################################## # # * It seems like nitpicking, but there actually are some cases where the # overall quality is better when doing this in the right order: Do # "without logo" before "with logo" # # # Start here ######################################## # root="/var/www/media.example.com/" shopt -s extglob shopt -s nullglob cd ${root}custom-jpg-without-logo; create_all_links_from_directory cd ${root}custom-jpg-logo; create_all_links_from_directory cd ${root}tools-jpg-without-logo; create_all_links_from_directory cd ${root}tools-jpg-logo; create_all_links_from_directory cd ${root}misc-jpg-without-logo; create_all_links_from_directory cd ${root}misc-jpg-logo; create_all_links_from_directory cd ${root}promotion-jpg-without-logo; create_all_links_from_directory cd ${root}promotion-jpg-logo; create_all_links_from_directory