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

2
  • 1
    same answer here, answers your question as well. Commented Jun 26, 2020 at 4: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). Commented Jun 26, 2020 at 5:55

1 Answer 1

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.

1

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.