Skip to content

Instantly share code, notes, and snippets.

@frontrangerider2004
Last active September 7, 2016 15:16
Show Gist options
  • Save frontrangerider2004/ccfefc1e1914ee14241cbb7826c56a3a to your computer and use it in GitHub Desktop.
Save frontrangerider2004/ccfefc1e1914ee14241cbb7826c56a3a to your computer and use it in GitHub Desktop.
Shows how to use while read loops and the find command to properly loop over the output of a find command.
#!/bin/bash
#######################################################################
# Examples of using the find commands
#######################################################################
# This is an unsafe and bad way to loop over output of find commands
# One should use the while read loop to avoid potential errors with the output
# of the find command. See below:
for file in $(find . -maxdepth 1 -type d -path Projects -prune -o -print);
do
printf "%s" "$file"
done
# Find all directories in the current dir and print their name while excluding
# a directory named 'Projects'.
# We use the double arrows to create a data stream when evaluating the output
# of a command for the while loop.
while read file
do
printf "%s\n" "$file"
done < <(find . -maxdepth 1 -type d -path Projects -prune -o -print)
# Find all directories in the current dir while ignoring hidden dirs and print
# while excluding a directory named 'Projects'.
# We use the double arrows to create a data stream when evaluating the output
# of a command for the while loop.
while read file
do
printf "$file"
done < <(find . -maxdepth 1 -type d -path Projects -prune -o -not -name ".*" -print)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment