0

I have written the following bash function to easily open files from the command line with their default application:

## Open files with their default application
function open {
    # If no arguments supplied, open current directory in Files application
    if [ $# -eq 0 ]; then
        xdg-open . &> /dev/null
    else
    # Else, open all files in the args with their default application
        for file in $@; do
            xdg-open "$file" &> /dev/null
        done
    fi
}

This function works mostly fine, however, it's not able to deal with filenames that have spaces in it. Even if the spaces are escaped or the filename is quoted, like this:

open file\ with\ spaces\ in\ name.txt && open "file with spaces in name.txt"

the function still does nothing when you try to open these files. If I take out the for-loop and have it just open the first argument that is passed to the function, there's no problem; the function is only not working when I enable it to support multiple arguments.

Is there a way to solve this problem? I do have a bash function that swaps out the spaces in a filename for underscores, but I'd prefer not to have to do that in order to use my open function on that file.

1
  • 3
    You have to quote $@ like this: for file in "$@" ; do
    – FedKad
    Jan 18, 2021 at 14:18

1 Answer 1

2

In order to make each positional parameter expand to a separate word, you need to double-quote $@ as well as the loop variable "$file". From man bash:

   @      Expands to the positional parameters, starting from  one.   When
          the  expansion  occurs  within  double  quotes,  each  parameter
          expands to a separate word.  That is, "$@" is equivalent to "$1"
          "$2"  ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.