I have problem with my for cycle, this is what I want:

for arg
array[index]=(`find $arg -type l -maxdepth $depth -printf "%p\n" `)

arg - positional arguments, only directories

This cycle go through the arguments and finds symbolic links and I want them to be stored in an array. If I run script with only one directory it works okay, but when I enter two or more directories it does not work. Any help ?

I want to work it like this, for example:

There are two arguments, each one is directory.

Cycle first set arg to first directory and then array is filled with symbolic links for example it will find 2 symbolic links so array[0] array[1] will be that links and then it should continue with second arg and there are for example 3 symbolic links and it should set them to array[2] array[3] array[4]

  • what shell? Did you miss a $ before the (, does the for need an in …, – ctrl-alt-delor Nov 15 '13 at 12:26

If we're talking ksh93 or bash (and GNU find), there's no multidimentional arrays (or arrays of arrays), you could do though:

index=0 IFS=$'\n'
set -f
for arg do
  eval "array_$index"'=($(find "$arg" -type l -maxdepth "$depth" -print))'

To have different arrays called array_0, array_1...

(the above assumes filenames don't contain newline characters).

If you want all the links merged into a single array, then:

set -f
array=($(find "$@" -type l -maxdepth "$depth" -print))

should be enough.

Using arrays or loops in shells are often a sign that you're not getting at the problem the right way.

For instance, if you want to find the deepest symlink (as your comment suggests), you'd do something like:

find "$@" -type l -print | awk -F/ '
   NF > n {deepest = $0; n=NF}
   END {print "Deepest:", deepest}'

awk is going to be a lot more efficient than the shell to process text and work with arrays. It is designed for that. Shells are not (and bash of all shells is one of the most inefficient ones at it). Shells are good at running commands (like awk or find), that's what they're designed for.

  • do you know how to count every / in every index of array ? i want to find out which symbolic link have the longest path so i want to make something like i will count every / in array[0] then array[1] and store it int new array for exm maxarray and in max array i will find maximum and then again i will go through array and count / and when count of / and max are equal i will echo that link – xpukm Nov 15 '13 at 13:05
  • and how to rewrite your scrip with awk that output will be like output in this command find -type l -printf "%p -> %l\n" and i want to count "/" only in %l can you help me ? because i have never used awk – xpukm Nov 20 '13 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.