如何提取 bash 脚本中的父文件夹?

How to extract the parent folder in bash script?

在 bash 脚本中,我想提取 pwd 的最后两个文件夹。

我这样做了:

value=`pwd`
echo "you are here : $value"
echo "the folder is: ${value##*/}"

拥有这个:

you are here: /home/user/folder1/folder2
the folder is folder2

现在我想提取父文件夹 (folder1)。

像这样,使用预定义变量PWD:

value="$PWD"
echo "you are here :$value"
echo "the folder is: ${value##*/}"
echo "the parent folder is $(basename "${PWD%/*}")"

您可以将最后一行替换为:

dir="${PWD%/*}"
echo "the parent folder is ${dir##*/}"

反引号 (`) 用于旧式命令替换,例如

foo=`command`

建议使用 foo=$(command) 语法。 $() 内的反斜杠处理并不令人惊讶,并且 $() 更容易嵌套。参见 http://mywiki.wooledge.org/BashFAQ/082

试试这个:

value=`pwd`
echo "you are here: $value"
echo "the folder is ${value##*/}"
parent="${value%/*}"
echo "the parent folder is ${parent##*/}"

为了得到这个:

you are here: /home/user/folder1/folder2
the folder is folder2
the parent folder is folder1

这是一个使用正则表达式的解决方案: 如果你想知道正则表达式是如何工作的,我建议你看一下 this site.

#!/bin/bash
value=$(pwd)
regex='.*\/([a-zA-Z0-9\._]*)\/([a-zA-Z0-9\._]*)$'
echo You are here: $value
echo The folder is: ${value##*/}
[[ $value =~ $regex ]]
echo Parent folder: ${BASH_REMATCH[1]}