Search code examples
linuxbashgnome

Function / alias that opens all files from glob expression


I'm trying to write a terminal function / alias that opens all files from whatever glob expression I want (eg, all files with the same extension).

I've tried to use both find -exec and find | xargs

This works:

$ find . -type f -name '*.eps' -exec gnome-open {} \;

this function (sourced on ~/.bashrc) only opens one file:

openall () { find . -type f -name "$1" -exec gnome-open {} \; ; }

I also tried the xargs route (which works, when written in the terminal):

$ find . -iname "*.eps" -print0 | xargs -0 gnome-open ;

which again only opens one file, while one this works:

$ find . -iname "*.eps" | xargs -n 1 gnome-open ;

the function (again, sourced on ~/.bashrc) doesn't:

openall () { find . -iname '$1' | xargs -n 1 gnome-open ; }

as it returns:

Usage: gnome-open <url>

I think I'm doing something wrong while passing the arguments, but I can't figure out what.


Solution

  • You're not showing how you call the functions that are failing.

    openall () { find . -type f -name "$1" -exec gnome-open {} \; ; }
    

    should work, but you need to quote the argument:

    openall "*.eps"
    

    Otherwise, the shell expands the pattern before calling openall, and your function picks only the first of the expanded arguments.

    openall () { find . -iname '$1' | xargs -n 1 gnome-open ; }
    

    Here you are using single quotes. This ignores all arguments and finds only files with the literal name $1.


    Maybe it's simpler to provide just a suffix instead of a pattern? That avoids quoting:

    openall () { find . -type f -name "*$1" -exec gnome-open {} \; ; }
    

    Note the * before $1. Call it like this:

    openall .eps