Prometheus
Prometheus

Reputation: 639

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 :

    path_to_file="/home/user/path/to/fileName.txt";
    IFS='/' read -ra split_path <<< "$path_to_file";
    file_name="${split_path[-1]}";

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.

Upvotes: 2

Views: 983

Answers (2)

tripleee
tripleee

Reputation: 189739

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##*/}

Upvotes: 5

Mustafa DOGRU
Mustafa DOGRU

Reputation: 4112

with basename ;

path_to_file="/home/user/path/to/fileName.txt";
file_name=$(basename "$path_to_file")
echo $file_name

with awk;

path_to_file="/home/user/path/to/fileName.txt";
file_name=$(echo $path_to_file | awk -F / '{print $NF}') 
echo $file_name

or while loop ;

path_to_file="/home/user/path/to/fileName.txt";
while IFS='/' read -ra split_path ; do
file_name="${split_path[-1]}";
echo $file_name
done <<<$path_to_file

Upvotes: 1

Related Questions