Prometheus Prometheus - 1 year ago 165
Linux Question

Bad array subscript while splitting a string in bash

I am trying to split a string using IFS looking at examples provided at many places. I want to get last element of the array after split, I am doing following to achieve goal :

IFS='/' read -ra split_path <<< "$path_to_file";

It gives the whole string separated by space in a single element in the array. When I run the last command I get error message saying "-bash: split_path: bad array subscript". What I am doing wrong which is not giving me separated elements in different index of array.

Answer Source

Bash 3.x does not understand -1 to mean the last element of an array. You want

echo "${split_path[${#split_path[@]}-1]}"

Notice also the quoting.

As others have pointed out, basename might be a better run for your money, or ${path_to_file##*/}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download