bash: extracting last two dirs for a pathname

前端 未结 7 1083
灰色年华
灰色年华 2021-02-12 12:42

I seem to have failed at something pretty simple, in bash. I have a string variable that holds the full path to a directory. I\'d like to assign the last two di

7条回答
  •  渐次进展
    2021-02-12 13:23

    I prefer to use the builtins as much as I can, to avoid create unnecessary processes. Because your script may be run under Cygwin or other OS whose process creation are very expensive.

    I think it's not so lengthy if you just want to extract two dirs:

    base1="${DIRNAME##*/}"
    dir1="${DIRNAME%/*}"
    DIRNAME2="${dir1##*/}/$base1"
    

    This can also avoid special char problems involved in executing another commands.

提交回复
热议问题