Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames
9# Determine the next available comment number
10if [ "$(ls -A comments)" ]; then
11 # Find the highest numbered comment file and set the comment_counter accordingly
12 comment_counter=$(ls comments | grep -Eo '[0-9]+' | sort -n | tail -1)13 comment_counter=$((comment_counter + 1))
14else
15 comment_counter=1
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.
Problematic code:
ls /directory | grep mystring
# or
rm $(ls | grep -v '\.c$')
Preferred code:
ls /directory/*mystring*
# or
# BASH
shopt -s extglob
rm -- !(*.c)
# POSIX
for f in ./*
do
case $f in
*.c) true;;
*) rm "$f";;
esac
done
Exceptions:
ls
has sorting options that are tricky to get right with other commands. If a specific order of files is needed,ls <sort options> | grep
might be the best alternative.- Network shares like AFS behave much faster using
ls
.