Search code examples
linuxbashif-statementgrepls

Bash - alternative for: ls | grep


I use the following pipe as variable in a script:

match=$( ls | grep -i "$search")

this is then used in an if statement:

if [ "$match" ]; then
    echo "matches found"
else
    echo "no matches found"
fi

what would be an alternative if I did not want to use find? ShellCheck recommends:

ls /directory/target_file_pattern

but I do not get the syntax right to get the same result. also I want no output when there are no matches for the if statement to work.


Solution

  • If you just want to tell if there exist any matches with bash you could use the builtin compgen like so:

    if compgen -G 'glob_pattern_like_your_grep' >/dev/null; then
        echo "matches found"
    else
        echo "no matches found"
    fi
    

    if you want to operate on the files that are matched, find is usually the right tool for the job:

    find . -name 'glob_pattern_like_your_grep' -exec 'your command to operate on each file that matches'
    

    the key though is that you have to use glob patterns, not regex type patterns.

    If your find supports it, you might be able to match a regex like

    find . -regex 'pattern'
    

    and use that in either the if or with -exec