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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With