Skip to content
koalaman edited this page Jan 5, 2018 · 16 revisions

Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames.

Problematic code:

ls /directory | grep mystring

or

rm $(ls | grep -v '\.c$')

Correct code:

echo /directory/*mystring*

or

# BASH
shopt -s extglob
rm -- !(*.c)

# POSIX
for f in ./*
do
  case $f of
    *.c) true;;
    *) rm "$f";;
  esac
done

Rationale:

Parsing ls is generally a bad idea because the output is fragile and human readable. To better handle non-alphanumeric filenames, use a glob. If you need more advanced matching than a glob can provide, use a for loop.

Exceptions:

None

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally