Search code examples
shelldash-shell

How to test for a character (or string) in a filename in dash


I have a string (a filename, actually) that I want to test whether they contain a character:

NEEDLE="-"
for file in mydirectory/*
do
   if [NEEDLE IS FOUND IN STRING]
   then
       # do something
   else
       # do something else
   fi
done

Basically this is the same question as String contains in Bash, except for dash instead of bash (ideally shell-neutral, which is usually the case with dash-code anyway)

The [[ operator does not exist in dash, therefore the answer to that question does not work.


Solution

  • use a case statement, no need to spawn an external program:

    NEEDLE="-"
    for file in mydirectory/*; do
        case "$file" in
            *"$NEEDLE"*) echo "do something" ;;
            *) echo "do something else" ;;
        esac
    done