21

This doesn't work:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d | basename

apparently basename cannot read from stdin - in any case basename requires at least one argument.

  • Are you simply looking to strip off the final directory name, or are you looking to find the parents of things that might be symbolic links from `$all_locks`? – ghoti Jun 09 '19 at 04:28
  • I am just trying to get the basename of each path resulting from find –  Jun 09 '19 at 04:30
  • So if `/path/to/this` is a symlink to `/some/other/place`, should your result be `/path/to` or `/some/other`? – ghoti Jun 09 '19 at 12:30

3 Answers3

28

To apply a command to every result of a piped operation, xargs is your friend. As it says on the man page I linked...

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input.

In this case that means it will take each result from your find command and run basename <find result>ad nauseum, until find has completed its search. I believe what you want is going to look a lot like this:

find "$all_locks" -mindepth 1 -maxdepth 1 -type d | xargs basename

Peter J. Mello
  • 414
  • 3
  • 9
6

Since mindepth and maxdepth are GNU extensions, using another one such as printf will not make it less portable.

find "$all_locks" -mindepth 1 -maxdepth 1 -type d -printf '%f\n'
oguz ismail
  • 1
  • 16
  • 47
  • 69
5

The problem here is basename doesn't accept the stdin and hence unnamed pipes may not be useful. I would like to modify your command a little bit. Let me know if it serves the purpose.

find -mindepth 1 -maxdepth 1 -type d -exec basename {}  \;

Note: Not enough reputation to comment, hence posting it here.

susenj
  • 342
  • 1
  • 4
  • 12
  • 2
    on ubuntu bash 4, I get `find: missing argument to '-exec'`...weird –  Jun 09 '19 at 04:12
  • 2
    @MrCholo, I hope you didn't miss a space between `{}` and \ ? Because, I can recreate your problem by erasing that space. – susenj Jun 09 '19 at 04:34