I've read a ton of answers that are close to what I need, but not exactly, and I can't figure out how to adapt them to my needs.

I'd like to take write a bash script that takes a source folder as an argument, and perform a bunch of operations on every file (of certain type) in that folder.


for file in $src_dir/*.jpg; do
    filename=`basename "$file"`

works if there are no spaces in src_dir, but I cannot figure out how to make this work if there are spaces. Usually "$src_dir" works, but this doesn't work with for file in .

EDIT: I should mention, I would like to be able to pass paths that contains variables that need expanding ($HOME, $MY_PROJECT_PATH etc. so single tick ' is also not ideal)


2 Answers 2


When you say it doesn't work with quotes, then I'm assuming that you have quoted the whole $src_dir/*.jpg bit. Then, yes, it would not work as * stops being a globbing character in a quoted string.

However, if you just quote $src_dir, it will work:


for pathname in "$src_dir"/*.jpg; do
    name_noext=$( basename -- "$pathname" .jpg )

This leaves * unquoted, which makes the shell use it as a globbing character.

As for your edit: When the script is called with e.g. $HOME, I'm assuming it is called with the expansion of the HOME variable, not with the literal string $HOME. It would be incredibly problematic if the script would have to test whether the supplied directory path contained literal variable names, which would include having to decide whether the string $HOME was a variable or the literal name of a directory (which it could technically be). This is unrelated to the expansion of $src_dir for your loop.

  • thanks! Very pleasantly surprised that the answer is so simple :P
    – memo
    Commented Aug 29, 2021 at 10:46

You only need to double-quote src_dir. Also, if you don't want to pollute your shell with random variables, use a subshell: (src_dir=$1; for file in "$src_dir"/*.jpg; do ... done)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .