Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding executable files using ls and grep

Tags:

linux

grep

bash

ls

I have to write a script that finds all executable files in a directory. So I tried several ways to implement it and they actually work. But I wonder if there is a nicer way to do so.

So this was my first approach:

ls -Fla | grep \*$ 

This works fine, because the -F flag does the work for me and adds to each executable file an asterisk, but let's say I don't like the asterisk sign.

So this was the second approach:

ls -la | grep -E ^-.{2}x  

This too works fine, I want a dash as first character, then I'm not interested in the next two characters and the fourth character must be a x.

But there's a bit of ambiguity in the requirements, because I don't know whether I have to check for user, group or other executable permission. So this would work:

ls -la | grep -E ^-.{2}x\|^-.{5}x\|^-.{8}x 

So I'm testing the fourth, seventh and tenth character to be a x.

Now my real question, is there a better solution using ls and grep with regex to say:

I want to grep only those files, having at least one x in the ten first characters of a line produced by ls -la

like image 882
k13n Avatar asked Oct 18 '11 19:10

k13n


2 Answers

Do you need to use ls? You can use find to do the same:

find . -maxdepth 1 -perm -111 -type f 

will return all executable files in the current directory. Remove the -maxdepth flag to traverse all child directories.

You could try this terribleness but it might match files that contain strings that look like permissions.

ls -lsa | grep -E "[d\-](([rw\-]{2})x){1,3}" 
like image 51
Dan Avatar answered Sep 29 '22 23:09

Dan


If you absolutely must use ls and grep, this works:

ls -Fla | grep '^\S*x\S*' 

It matches lines where the first word (non-whitespace) contains at least one 'x'.

Find is the perfect tool for this. This finds all files (-type f) that are executable:

find . -type f -executable 

If you don't want it to recursively list all executables, use maxdepth:

find . -maxdepth 1 -type f -executable 
like image 32
rmmh Avatar answered Sep 29 '22 23:09

rmmh