Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am new to bash script. I am taking some input from user and checking details about that.



I take the above string as an input and want to retrieve one.txt, I need to further proceed with one.txt.

I am not putting up the whole question as I want to put inputs from my side.

I am stuck at this point and without splitting up the string, I will not be able to move ahead.

share|improve this question
You really should just ask your real question. – bahamat Oct 9 '13 at 5:06
@bahamat I want to get one.txt from input. – Death Metal Oct 9 '13 at 5:07
up vote 4 down vote accepted

@Jordanm has already given you the canonical answer that works for any string. If you are dealing specifically with paths, you can also use the programs basename and dirname:

   basename - strip directory and suffix from filenames
   dirname - strip last component from file name

For example:

$ file="$HOME/Documents/test/one.txt"
$ dir=$(dirname "$file");
$ name=$(basename "$file");
$ echo "The file called $name is in the directory $dir"
The file called one.txt is in the directory /home/terdon/Documents/test
share|improve this answer

This is a common task that can be handled by a parameter expansion in any POSIX shell.

file=${path##*/} # file contains one.txt

Another common method is to use the basename program.

file=$(basename "$path")

The only disadvantage is having to spawn an external program. It's main advantage is that it properly handles paths with a trailing /.

share|improve this answer
To be pedantic, "$(basename "$path")" is wrong in the unlikely event that $path ends with a newline. This is because a) basename adds an extra newline on the end, and b) $(command) strips all trailing newlines. To make it work requires a perverse workaround, something like this: path=$'/tmp/evil\n'; file="$(basename "$path"; printf x)"; strip=$'\nx'; fixed="${file%%$strip}" – Matt Oct 9 '13 at 6:04

If you're doing this with filenames, use the basename command:

$ basename $HOME/Documents/test/one.txt


$ FILE=$(basename basename $HOME/Documents/test/one.txt)
$ echo $FILE

If you need to split arbitrary strings with arbitrary delimiters it's a little bit of magic. Read the string into an array and set the input field separator to the delimiter.

Here's an example:

$ IFS='/' read -a my_array <<< "$HOME/Documents/test/one.txt"
$ ARRAY_LENGTH=$(( ${#my_array[@]} - 1 ))
$ echo "${my_array[$ARRAY_LENGTH]}"
share|improve this answer
Thank you for your inputs! :) – Death Metal Oct 10 '13 at 4:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.