How to properly handle wildcard expansion in a bash shell script?


Question

#!/bin/bash

hello()
{
    SRC=$1
    DEST=$2

    for IP in `cat /opt/ankit/configs/machine.configs` ; do
        echo $SRC | grep '*' > /dev/null
        if test `echo $?` -eq 0 ; then
            for STAR in $SRC ; do
                echo -en "$IP"
                echo -en "\n\t ARG1=$STAR ARG2=$2\n\n"
            done
        else
            echo -en "$IP"
            echo -en "\n\t ARG1=$SRC ARG2=$DEST\n\n"
        fi
    done
}

hello $1 $2

The above is the shell script which I provide source (SRC) & desitnation (DEST) path. It worked fine when I did not put in a SRC path with wild card ''. When I run this shell script and give ''.pdf or '*'as follows:

root@ankit1:~/as_prac# ./test.sh /home/dev/Examples/*.pdf /ankit_test/as

I get the following output:

192.168.1.6
ARG1=/home/dev/Examples/case_Contact.pdf ARG2=/home/dev/Examples/case_howard_county_library.pdf

The DEST is /ankit_test/as but DEST also get manupulated due to '*'. The expected answer is

ARG1=/home/dev/Examples/case_Contact.pdf ARG2=/ankit_test/as

So, if you understand what I am trying to do, please help me out to solve this BUG. I'll be grateful to you.

Thanks in advance!!!

I need to know exactly how I use '*.pdf' in my program one by one without disturbing DEST.

1
3
11/3/2008 10:52:20 AM

Your script needs more work. Even after escaping the wildcard, you won't get your expected answer. You will get:

ARG1=/home/dev/Examples/*.pdf ARG2=/ankit__test/as

Try the following instead:

for IP in `cat /opt/ankit/configs/machine.configs`
do
    for i in $SRC
    do
        echo -en "$IP"
        echo -en "\n\t ARG1=$i ARG2=$DEST\n\n"
    done
done

Run it like this:

root@ankit1:~/as_prac# ./test.sh "/home/dev/Examples/*.pdf" /ankit__test/as
4
11/3/2008 10:40:11 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon