Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with `*` expansion when there are no files

Tags:

bash

I am making a shell script that allows you to select a file from a directory using YAD. I am doing this:

  list='';
  exc='!'
  for f in "$SHOTS_NOT_CONVERTED_DIR"/*;do
    f=`basename $f`
    list="${list}${exc}${f}"
  done

The problem is that if there are no files in that directory, I end up with a selection with *.

What's the easiest, most elegant way to make this work in Bash? The goal is to have an empty list if there are no files there.

like image 354
Merc Avatar asked Sep 15 '25 01:09

Merc


1 Answers

* expansion is called a glob expressions. The bash manual calls it filename expansion.

You need to set the nullglob option. Doing so gives you an empty result if the glob expression does not find files:

shopt -s nullglob

list='';
exc='!'
for f in "$SHOTS_NOT_CONVERTED_DIR"/*;do
    # Btw, use $() instead of ``
    f=$(basename "$f")
    list="${list}${exc}${f}"
done
like image 84
hek2mgl Avatar answered Sep 17 '25 16:09

hek2mgl