2

Whenever glob pattern match fails, it stops the whole job. For instance,

$ mv *.jpg *.png folder1 && blahblah
mv: cannot stat `*.jpg': No such file or directory

*.png isn't moved to folder1 and blahblah is not run.

And the script below works only for the case when both .[A-z]* and * succeed.

#!/bin/bash
cd $1
du -sk .[A-z]* *| sort -rn | head

How do I make globbing fail gracefully, at most only displaying warnings, but never stopping the job?

Justin R.
  • 23,435
  • 23
  • 108
  • 157
Yoo
  • 17,526
  • 6
  • 41
  • 47

2 Answers2

5

In Bash, shopt -s nullglob will allow a failed glob to expand to nothing with no errors.

ephemient
  • 198,619
  • 38
  • 280
  • 391
  • 1
    nullglob solves most of the problem, but not quite all; if none of the globs match, you wind up with something like `mv folder1 && blahblah` (you get a usage message from mv, and blahblah doesn't run). Completely solving it is more complicated, partly because you have to define what should happen if there are no files to operate on. You wind up doing things like `file_list=(*.jpg *.png); if [[ ${#file_list[@]} -gt 0 ]]; then mv "${file_list[@]}" folder1 && ...` – Gordon Davisson Oct 20 '09 at 19:34
0

then use a loop. KISS

for files in jpg png
do
  mv *.${files} /destination 2>/dev/null && do_something 
done
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 1
    Not only is this slower, but also it still emits `mv: cannot stat '*jpg': No such file or directory`. – ephemient Oct 21 '09 at 00:41
  • please look at the whole thing carefully again before you comment. I jolly well know its slow. but it gets the job done. A single command "mv *jpg *png folder && touch dummy" for example, will not work as per OP's case. But if you introduce a for loop, the dummy file will be created because now, we are doing each file types one by one. – ghostdog74 Oct 21 '09 at 01:42
  • This now runs `do_something` twice if both `*.jpg` and `*.png` globs are non-null, and still emits the message. I suppose you may have intended to write `mv *.$files 2>/dev/null && do_something`. – ephemient Oct 21 '09 at 02:56