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
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
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
.
read
is also wrong for arbitrary paths asread
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 "" (inbash
note that other shells useread -A array
to read into an array). – Stéphane Chazelas Jun 26 '20 at 05:55