2

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

${path_to_file##*/}. -1 should work in newer bash versions though. (It works for me in 4.3.11)
@PSkocik Thanks for the corrections. Yeah, this is Bash 3, which I imagine is what the OP is struggling with.
Although my Bash version is 4.1.2. Your answer is what I am looking for.
1

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

1 Comment

Variables which contain file names should always be in double quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.