Find the answer to your Linux question:
Results 1 to 4 of 4
Hello ! I am trying to write a script which can read the names of all folders within a given folder into separate variables. In effect, if a folder contains ...
  1. #1
    vij
    vij is offline
    Just Joined!
    Join Date
    Jul 2010
    Location
    France
    Posts
    1

    Read a Foldername into a variable

    Hello !

    I am trying to write a script which can read the names of all folders within a given folder into separate variables. In effect, if a folder contains a folder "Folder1", "Folder2", "Folder3", the script would read those names into variables such as:

    Variable1 = "Folder1"
    Variable2 = "Folder2"
    Variable3 = "Folder3"

    I have tried fiddling with the find . command, but without any success. Any ideas ?

  2. #2
    Linux Enthusiast Kloschüssel's Avatar
    Join Date
    Oct 2005
    Location
    Italy
    Posts
    717
    assuming you are doing bashy things, try this:

    Code:
    for i in ./*; do echo $i; done;
    anyway variables should be assigned without whitespaces as prefix or postfix of the equality. that means, your code should be written as:

    Code:
    Variable1="Folder1"
    Variable2="Folder2"
    Variable3="Folder3"

  3. #3
    Just Joined!
    Join Date
    Feb 2009
    Location
    Southport, England
    Posts
    31
    Yes, and to follow on, you can use an IF statement to check if they are directories to distinguish them from regular files, i.e.:

    Code:
    for file in *; do
       if [ -d $file ]; then
          echo $file
       fi
    done
    I'm not sure how to do arrays, which is probably a good way to do this; sorry.

  4. #4
    Linux Enthusiast Kloschüssel's Avatar
    Join Date
    Oct 2005
    Location
    Italy
    Posts
    717
    well, an array is simple as that:

    Code:
    array=()
    i=0
    for file in *; do
       if [ -d $file ]; then
          array[$i]=$file;
          i=`expr $i + 1`
       fi
    done
    echo ${array[*]}
    all code shipped for free, but without any warranties HAPPY BASHing!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...