Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read glob from command line in Bash

Tags:

bash

glob

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?

like image 369
Hari Menon Avatar asked Feb 21 '11 08:02

Hari Menon


2 Answers

You need to access all the contents of the parameters that are passed to the script. The glob is expanded by the shell before your script is executed.

You could copy the array:

#!/bin/bash
FILES=("$@")
for f in "${FILES[@]}"
do
    echo "Processing $f file..."
    echo "$f"
done

Or iterate directly:

#!/bin/bash
for f     # equivalent to for f in "$@"
do
    echo "Processing $f file..."
    echo "$f"
done

Or use shift:

#!/bin/bash
while (($# > 0))
do
    echo "Processing $1 file..."
    echo "$1"
    shift
done
like image 81
Dennis Williamson Avatar answered Sep 23 '22 03:09

Dennis Williamson


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.

like image 34
Eugene Yarmash Avatar answered Sep 24 '22 03:09

Eugene Yarmash