taT4Nix | Pattern-based Files Listing..

I have come across this situation many times since beginning to write my first shell script few months back, i.e. listing files based on pattern using command line. I have followed the following approach many-a-times;

$> ls -1 *some_pattern*

Ideally, it should list files/directories line-by-line matching the pattern. However, if there’s no file based on this pattern in the PWD, then error is displayed on the screen, “No such file or directory”.

Now, if I have to do similar listing inside shell scripts? and I don’t want to see this error message  to be displayed, like inside if-condition or some other construct. Then, one may use the following approach;

$> if [[ ! -z $(ls -1 | grep *some_pattern*) ]]; then echo "Files found based on some_pattern"; fi

Well, you may use every possible option of grep command and variety of regular expressions to do the search. Even, if they are no such files/directories in the PWD, you won’t get any error message. Instead, there won’t be any output in display.

That’s helpful inside the shell scripts. Try it yourself to know the difference and improve your shell scripts. This way you would specific files/directories listing based on the pattern.

Tips To Remember

However, it may happen that you are passing wrong pattern to grep command, which would still show no output ideally. That doesn’t mean you’re on the right track. So, you may use the above two approaches, in that very order to verify whether you are able to create regular expression/pattern or not.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s