Search code examples
bashpattern-matching

How do we match a suffix in a string in bash?


I want to check if an input parameter ends with ".c"? How do I check that? Here is what I got so far (Thanks for your help):

#!/bin/bash

for i in $@
do
    if [$i ends with ".c"]
    then
            echo "YES"
        fi
done

Solution

  • A classical case for case!

    case $i in *.c) echo Yes;; esac
    

    Yes, the syntax is arcane, but you get used to it quickly. Unlike various Bash and POSIX extensions, this is portable all the way back to the original Bourne shell.

    Tangentially, you need double quotes around "$@" in order for it to correctly handle quoted arguments.