0

Why is $PARTS blank

DIR=/Users/ishandutta2007/Projects/yo
IFS='/' read -ra PARTS <<< "$DIR"
echo $PARTS

Edit: Thanks for suggesting alternate ways, but I am looking to fix the issue with IFS

  • 1
    same answer here, answers your question as well. – αғsнιη Jun 26 '20 at 04:36
  • Using read is also wrong for arbitrary paths as read only considers the first line of the path. Also note that /a/b/ is split into "", "a" and "b" while /a/b// is split into "", "a", "b" and "" (in bash note that other shells use read -A array to read into an array). – Stéphane Chazelas Jun 26 '20 at 05:55

1 Answers1

4

The array is not blank, $PARTS expands to the first element of the array which happens to be empty and is the same as ${PARTS[0]}:

$ declare -p PARTS
declare -a PARTS=([0]="" [1]="Users" [2]="ishandutta2007" [3]="Projects" [4]="yo")

To print all array elements as separate words use "${PARTS[@]}":

$ printf '%s\n' "${PARTS[@]}"

Users ishandutta2007 Projects yo

To get the last element you can use a negative index:

$ echo "${PARTS[-1]}"
yo

But it's easier to get the last element using a parameter expansion:

$ echo "${DIR##*/}"
yo

This removes the longest prefix pattern */ from DIR.

Freddy
  • 25,565