Search code examples
bashglob

Read glob from command line in Bash


How do I read a glob in Bash from command line? I tried this and it only picks up the first file in the glob:

#!/bin/bash
shopt -s nullglob
FILES=$1
for f in $FILES
do
  echo "Processing $f file..."
  echo $f
done

Let's say my script is script.sh. I want to call it like sh script.sh /home/hss/* 4 gz (where /home/hss/*, 4 and gz are the command line arguments). When I try the above script, it reads only the first file. Any ideas?


Solution

  • You need to quote any parameters which contain shell meta-characters when calling the script, to avoid pathname expansion (by your current shell):

    sh script.sh "/home/hss/*" 4 gz
    

    Thus $1 will be assigned the pattern and not the first matched file.