Skip to content

Instantly share code, notes, and snippets.

@query
Last active December 29, 2015 05:29
Show Gist options
  • Select an option

  • Save query/7621885 to your computer and use it in GitHub Desktop.

Select an option

Save query/7621885 to your computer and use it in GitHub Desktop.

Revisions

  1. query revised this gist Jan 6, 2015. 1 changed file with 16 additions and 7 deletions.
    23 changes: 16 additions & 7 deletions randopen.bash
    Original file line number Diff line number Diff line change
    @@ -1,19 +1,26 @@
    #!/bin/bash
    #
    # Open a random file selected from the directory $1, or the current
    # directory if no arguments are given, and its subdirectories.
    # randopen.bash [-n] [DIR]
    #
    # Requires at least bash 3.1.
    # 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
    # The parentheses force recursion in a subshell, so that $i
    # doesn't get clobbered.
    [[ -d "$i" ]] && (search_recursive "$i")
    [[ -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?
    @@ -23,4 +30,6 @@ while read -d '' -r; do
    done < <(search_recursive "$dir")
    # Are there any files in the directory?
    [[ ${#files[@]} -gt 0 ]] || exit 1
    open "${files[$((RANDOM % ${#files[@]}))]}"
    file="${files[$((RANDOM % ${#files[@]}))]}"
    echo "$file"
    [[ -z $dry_run ]] && open "$file"
  2. query created this gist Nov 24, 2013.
    26 changes: 26 additions & 0 deletions randopen.bash
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    #!/bin/bash
    #
    # Open a random file selected from the directory $1, or the current
    # directory if no arguments are given, and its subdirectories.
    #
    # Requires at least bash 3.1.

    search_recursive() {
    for i in "$1"/*; do
    # The parentheses force recursion in a subshell, so that $i
    # doesn't get clobbered.
    [[ -d "$i" ]] && (search_recursive "$i")
    [[ -f "$i" ]] && echo -ne "$i\0"
    done
    }

    # 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
    open "${files[$((RANDOM % ${#files[@]}))]}"