如何通过管道获取路径的basename?现有find+basename命令执行失败
find Got it, let's break down why your original command fails first: basename doesn't read input from standard input (stdin) by default—it requires explicit path arguments. Here are three solid solutions to get the basename of each directory path returned by your find command:
1. Use find with -exec (Most Reliable)
Instead of piping to basename, use find's built-in -exec option to pass each found path directly to basename. This avoids any issues with spaces or special characters in paths.
Basic version (runs basename once per path):
find "$all_locks" -mindepth 1 -maxdepth 1 -type d -exec basename {} \;
Efficient version (bundles multiple paths into one basename call):
find "$all_locks" -mindepth 1 -maxdepth 1 -type d -exec basename {} +
The + tells find to pass as many paths as possible to a single basename process, which is faster for large numbers of directories.
2. Use xargs with find (Pipe-Friendly)
If you prefer using a pipe, xargs can convert the stdin output from find into arguments for basename. To handle paths with spaces or special characters, use -print0 with find and -0 with xargs:
find "$all_locks" -mindepth 1 -maxdepth 1 -type d -print0 | xargs -0 basename
The -print0 option makes find output paths separated by null characters instead of newlines, and -0 tells xargs to read those null-separated values—this prevents broken parsing for paths with spaces, tabs, or newlines.
3. Use Bash Parameter Expansion (Script-Friendly)
If you're working within a Bash script, you can loop through the find results and use Bash's built-in parameter expansion to extract the basename directly, no external basename command needed:
find "$all_locks" -mindepth 1 -maxdepth 1 -type d | while IFS= read -r dir_path; do echo "${dir_path##*/}" done
IFS=ensures leading/trailing spaces are preserved in the path.read -rprevents backslashes from being treated as escape characters.${dir_path##*/}strips everything up to and including the last/in the path, giving you the basename.
内容的提问来源于stack exchange,提问作者user5047085

