1

I want a user to input the filename which could be reside at any location but the name of the file is fixed in end .i.e. abc. txt

Let suppose the the user inputs the file name as /usr/test/abc.txt which comes in second positional parameter in my script

I want to make below statement as true how can I achieve this

if [ $2 == ..../abc.txt ]

Thanks, Ruchir

Ruchir Bharadwaj
  • 1,132
  • 4
  • 15
  • 31

4 Answers4

4

Let suppose the the user inputs the file name as /usr/test/abc.txt which comes in second positional parameter in my script

I want to make below statement as true how can I achieve this

Use this if condition using shell glob:

if [[ "/$2" == *"/abc.txt" ]]; then
    echo "valid match"
fi
Community
  • 1
  • 1
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can use basename to get the last component of the filename.

prompt> cat foo.sh
#!/bin/sh

if [ "abc.txt" == `basename $2` ]; then
    echo "found .../abc.txt"
fi

prompt> foo.sh foo /a/b/c/abc.txt
found .../abc/txt
Arun Taylor
  • 1,574
  • 8
  • 5
0
if [[ $2 == *"/abc.txt" ]]; then
   echo "It ends with abc.txt";
fi

Why [[ ]] works compared to [ ] is explained here...

"[ ]" vs. "[[ ]]" in Bash shell

Community
  • 1
  • 1
iamauser
  • 11,119
  • 5
  • 34
  • 52
0

you could do:

if ( echo "$2" | grep 'abc.txt$' >/dev/null ) ; then ... ; else .... ; fi

or

if ( echo "$2" | grep '/abc.txt$' >/dev/null ) ; then ... ; else .... ; fi

(if you need that "/" too ?)

Olivier Dulac
  • 3,695
  • 16
  • 31