Skip to content

Files

Latest commit

 

History

History
46 lines (32 loc) · 744 Bytes

SC2010.md

File metadata and controls

46 lines (32 loc) · 744 Bytes

Pattern: Parsing ls in shell script

Issue: -

Description

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.

Example of incorrect code:

ls /directory | grep somestring

or

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

Example of correct code:

echo /directory/*somestring*

or

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

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

Further Reading