0

I'm trying to take a full path directory and extract the every path out of it. For example

fullpath="/home/me/something/file"

/home/me/something/file
/home/me/something
/home/me
/home

My attempt but I haven't been able to figure out how to bring the paths out.

IFS=$'/'
                for i in $restorepath
                do
                     echo $i
                      if [ -d $i ]; then
                        echo dir exists
                       fi

                done
                unset IFS
user3590149
  • 1,525
  • 7
  • 22
  • 25
  • http://stackoverflow.com/questions/10586153/bash-split-string-into-array that might point you in the right direction. – John Jun 26 '14 at 00:23
  • 1
    Is this a xyproblem for "how do I create all required parent directories for a path?" if so, `mkdir -p`. – that other guy Jun 26 '14 at 01:05

2 Answers2

0

Couple of issues:

  • You're testing for a directory, but it looks like you're providing a file
  • There is no reason to unset IFS since the change won't get propagated to the parent shell. If you want to re-set to a default one for use later in this script, you can save the old one in some variable and reset it after, or just change it to something common like IFS=$'\t\n '

Try something like this

#!/bin/bash
fullpath="/home/me/something/file"
IFS='/'
for i in $fullpath; do
    subpath+="$i/"
    if [[ -e $subpath ]]; then
      echo "$subpath"
    elif [[ -e ${subpath%?} ]]; then
      echo "${subpath%?}" && break
    else
      break
    fi
done

Note, ${subpath%?} chops off the last character (? = single character wildcard in bash), in case you entered a file and not a directory as input. Also it's safe to break the loop if a subpath doesn't exist, since that implies no descendant of it can exist.

Reinstate Monica Please
  • 11,123
  • 3
  • 27
  • 48
0

Been a while since I did bash scripting, and this is a total hackish and untested way to do it, but without knowing what you are trying to do, it seems to me you should be able to do something like:

fullpath="/home/me/something/file
array=(${fullpath//// })
for i in "${!array[@]}"
do
    if i <= 4
        echo "$i=>${array[i]}"
done
for i in "${!array[@]}"
do
    if i <= 3
        echo "$i=>${array[i]}"
done
for i in "${!array[@]}"
do
    if i <= 2
        echo "$i=>${array[i]}"
done
for i in "${!array[@]}"
do
    if i <= 1
        echo "$i=>${array[i]}"
done
vapcguy
  • 7,097
  • 1
  • 56
  • 52