0

I am writing a bash script that will take a list of filenames as an argument. It will generally be used with wildcards.

Right now, the script just prints the files:

#!/bin/bash
for file in $@
do
    echo "Processing $file" 
done

The problem is when using a wildcard, and the file list has filenames that contain spaces. For example, if I have two files file1.jpg and file two.jpg, and I run ./myscript.sh *.jpg my output is

Processing file1.jpg
Processing file
Processing two.jpg

How do I make it recognize "file two.jpg" as one thing instead of two things? Note that the wildcard could be just * and files are not guaranteed to have an extension.

I am running this on a Mac, using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21)

Ben Holness
  • 2,457
  • 3
  • 28
  • 49
  • 2
    You need `"$@"`. This is an extremely common FAQ. – tripleee Dec 18 '22 at 12:38
  • Thanks. It is hard to find with search because the results are flooded with how to do it for non-wildcard situations and how to do other wildcard things not related to this! – Ben Holness Dec 18 '22 at 12:41
  • Yeah, I'm afraid the duplicate I found is also less than ideal but some of the answers there discuss this solution. – tripleee Dec 18 '22 at 12:51
  • See [Accessing bash command line args $@ vs $*](https://stackoverflow.com/q/12314451/4154375). – pjh Dec 19 '22 at 00:21
  • [Shellcheck](https://www.shellcheck.net/) identifies the problem, and links to an explanation of how to fix it ([SC2068](https://www.shellcheck.net/wiki/SC2068)). – pjh Dec 19 '22 at 00:25

0 Answers0