Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting parent's directory name by piping the results of dirname to basename in a Bash script

Given a path like this test/90_2a5/Windows

I am trying to get the result 90_2a5 using the commands dirname to get the path and after basename to get the name.

The problem occurs when i try to make it in a single line trying to pipe the results from dirname to basename.

I have tried this but seems that i am using it the wrong way.

path="test/90_2a5/Windows"   
finalName= basename var | dirname $path  
echo "$finalName"

The problem is that the finalName is an empty string, meaning that the results from dirname are not redirecting.

like image 341
stratis Avatar asked May 31 '13 10:05

stratis


2 Answers

You don't pipe them, but rather pass them as parameters:

finalName=$(basename -- "$(dirname -- "$path")")

Some commands quite simply do not accept input streams, but only parameters:

$ echo foo/bar | basename
basename: missing operand
Try `basename --help' for more information.
$ basename foo/bar
bar
like image 155
l0b0 Avatar answered Oct 04 '22 10:10

l0b0


$ echo 'test/90_2a5/Windows' | xargs dirname | xargs basename
90_2a5
like image 30
Rafael Avatar answered Oct 04 '22 10:10

Rafael