Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
hi,
i'm during with writing small bash script program that will perform a recursive search of subdirectories searching for the longes named file, with given a directory name as an argument.
can anybody tell me how can i do it.
thank
chui

longest () { recurse () { for file in $(/bin/ls $1) ; do fqfn=$1/$file ; [[ -d $fqfn ]] && recurse $fqfn ; [[ ${#file} -gt $len ]] && { len=${#file} name=$fqfn; } ; done ; } ; recurse $1 ; echo -e "\033[1;37m$len \033[0;33m$name" ; unset name len recurse ; }
... is one way.

hi,
i have try the coding that been post but i still have know idea how it done and i can't get what i want. is there any other coding that is more easy to understand, or can pls make the coding more in the script form.
thank
chui

The code above is a single line shell function: 'longest'. The idea is that you can cut and paste it into your terminal and use it immediately:
$> longest directory_name
You could also add it to your .bashrc file but if you really want it as an independent script file you need only remove the outer function to leave you with a file looking like this:
#!/bin/bash
recurse () {
for file in $(/bin/ls $1)
do fqfn=$1/$file
[[ -d $fqfn ]] && recurse $fqfn
[[ ${#file} -gt $len ]] && { len=${#file} name=$fqfn; }
done ; }recurse $1
echo -e "\033[1;37m$len \033[0;33m$name"# end of file
I hope that makes it clearer. You can see that the recurse function, called with the parameter $1, lists the contents of the directory $1 then tests to see if each file is a directory and if it is, it calls itself again. When it has finished, it echoes the result to the terminal (in colour for added clarity).
You can easily change or remove the colours if you dont like them and you could also improve the script in many other ways, for example by testing $1 at the beginning to make sure it is a directory and printing an error message if it is not.

not to detract from Wolfbone and the fact it works, how about:
len=0
for f in $(find $1 -type f -printf '%f\n')
do
[ ${#f} -gt $len ] && len=${#f}
done
echo $lenBTW,
I was not aware of ${#..} - thnx

I like Dlonra's version. If you want to run the script on Windows systems (where you have the file names with spaces in them), change the IFS to a carriage return.
IFS="
"Handy when writing scripts where you have Cygwin installed on your Windows system.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |