menteith
menteith

Reputation: 678

Check if an argument passed to a bash script is a file of a certain extension

I would like to check if

I have already dealt with the first and second requirement but I cannot deal with the last. My attemp is as follows:

if [ $# -eq 1 ] && [ -f $1 ] && [ ${"$1": -5} == ".epub" ]; then

Upvotes: 3

Views: 1168

Answers (1)

John1024
John1024

Reputation: 113834

Replace:

${"$1": -5}

With:

${1: -5}

Also, just in case the file name has spaces in it, apply double-quotes:

[ $# -eq 1 ] && [ -f "$1" ] && [ "${1: -5}" == ".epub" ]

Aside: Compatibility

Lastly, neither == not ${1: -5} are POSIX. If you want POSIX compatibility, use:

 [ $# -eq 1 ] && [ -f "$1" ] && [ "${1%.epub}" != "$1" ]

This will work not just with bash but with many other shells as well.

Upvotes: 1

Related Questions