Last active
December 29, 2015 05:29
-
-
Save query/7621885 to your computer and use it in GitHub Desktop.
Open a random file selected from a specified directory and its subdirectories.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# randopen.bash [-n] [DIR] | |
# | |
# Choose a random file selected from the directory DIR, or the current | |
# directory if it is not given, and its subdirectories. Output the | |
# selected file's name, and open it unless the `-n` option is given. | |
# | |
# Requires at least bash 3.1. `open` is specific to OS X and should be | |
# replaced on other platforms (e.g., `xdg-open`). | |
search_recursive() { | |
local i | |
for i in "$1"/*; do | |
[[ -d "$i" ]] && search_recursive "$i" | |
[[ -f "$i" ]] && echo -ne "$i\0" | |
done | |
} | |
if [[ $1 == "-n" ]]; then | |
dry_run=1 | |
shift | |
fi | |
# Use the current directory if no argument is specified. | |
dir=${1:-.} | |
# Does the directory exist? | |
[[ -d "$dir" ]] || exit 1 | |
while read -d '' -r; do | |
files+=("$REPLY") | |
done < <(search_recursive "$dir") | |
# Are there any files in the directory? | |
[[ ${#files[@]} -gt 0 ]] || exit 1 | |
file="${files[$((RANDOM % ${#files[@]}))]}" | |
echo "$file" | |
[[ -z $dry_run ]] && open "$file" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment