Find the answer to your Linux question:
Results 1 to 2 of 2
Hi Linux experts, I am a beginner at Linux. Is there any way I can extract subdirectory name into a variable. I am trying to create symbolic links. I know ...
  1. #1
    Just Joined!
    Join Date
    Jan 2011
    Posts
    1

    Post help extracting subdirectory names into variable

    Hi Linux experts,

    I am a beginner at Linux. Is there any way I can extract subdirectory name into a variable.

    I am trying to create symbolic links. I know how to do that one directory at a time.

    For example,

    Fruit_directory has subdirectories
    apple
    orange
    banana
    prune
    mango
    grapes
    ....

    ln -s orange/ 1
    ln -s banana/ 2
    ..etc

    But instead of writing one by one, I would like to run that in a for-loop. Is there any way I can read the subdirectory names into a variable (eg., subdirectory) so that I can use that variable (eg., $subdirectory) in creating symbolic links eg.,

    for ((x=1; x<= 10; x+=1))
    do
    ln -s $subdirectory $x
    done

    I am manipulating several hundred directories and would like to automate it in a loop. It would help me a lot. Thanks.

  2. #2
    Just Joined!
    Join Date
    Dec 2010
    Posts
    16
    I haven't tested it thoroughly but this should work unless your directory names contain spaces:

    Code:
    for subdirectory in $(find /where/to/start/* -type d -prune)
    do
       for ((x=1; x<= 10; x+=1))
       do
          ln -s $subdirectory $x
       done
    done
    The option -type d makes find only deliver directories.
    The option -prune prevents find from descending into subdirectories.

    To better understand, you may first try with and without -prune:

    Code:
    for subdir in $(find /where/to/start/* -type d -prune); do echo $subdir; done

Posting Permissions

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