Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

#!/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

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

like image 625
iankits Avatar asked Dec 05 '25 09:12

iankits


2 Answers

The shell will expand wildcards unless you escape them, so for example if you have

$ ls
one.pdf two.pdf three.pdf

and run your script as

./test.sh *.pdf /ankit__test/as

it will be the same as

./test.sh one.pdf two.pdf three.pdf /ankit__test/as

which is not what you expect. Doing

./test.sh \*.pdf /ankit__test/as

should work.

like image 60
agnul Avatar answered Dec 08 '25 00:12

agnul


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
like image 45
dogbane Avatar answered Dec 08 '25 00:12

dogbane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!