bash 如何在bash中获取给定路径的根目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24631866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How-To get root directory of given path in bash?
提问by user2966991
My script:
我的脚本:
#!/usr/bin/env bash
PATH=/home/user/example/foo/bar
mkdir -p /tmp/backup$PATH
And now I want to get first folder of "$PATH": /home/
现在我想获得“$PATH”的第一个文件夹:/home/
cd /tmp/backup
rm -rf ./home/
cd - > /dev/null
How can I always detect the first folder like the example above? "dirname $PATH" just returns "/home/user/example/foo/".
我怎样才能像上面的例子一样检测第一个文件夹?"dirname $PATH" 只返回 "/home/user/example/foo/"。
Thanks in advance! :)
提前致谢!:)
回答by user2966991
I've found a solution:
我找到了一个解决方案:
#/usr/bin/env bash
DIRECTORY="/home/user/example/foo/bar"
BASE_DIRECTORY=$(echo "$DIRECTORY" | cut -d "/" -f2)
echo "#$BASE_DIRECTORY#";
This returns always the first directory. In this example it would return following:
这总是返回第一个目录。在此示例中,它将返回以下内容:
#home#
Thanks to @condorwasabi for his idea with awk! :)
感谢@condorwasabi 对 awk 的想法!:)
回答by konsolebox
If PATH
always has an absolute form you can do tricks like
如果PATH
总是有一个绝对形式,你可以做一些技巧,比如
ROOT=${PATH#/} ROOT=/${ROOT%%/*}
Or
或者
IFS=/ read -ra T <<< "$PATH"
ROOT=/${T[1]}
However I should also add to that that it's better to use other variables and not to use PATH
as it would alter your search directories for binary files, unless you really intend to.
但是我还应该补充一点,最好使用其他变量而不是使用PATH
它,因为它会改变二进制文件的搜索目录,除非您真的打算这样做。
Also you can opt to convert your path to absolute form through readlink -f
or readlink -m
:
您也可以选择通过readlink -f
或将路径转换为绝对形式readlink -m
:
ABS=$(readlink -m "$PATH")
You can also refer to my function getabspath.
你也可以参考我的函数getabspath。
回答by condorwasabi
You can try this awk command:
你可以试试这个 awk 命令:
basedirectory=$(echo "$PATH" | awk -F "/" '{print }')
At this point basedirectory
will be the string homeThen you write:
此时basedirectory
将是字符串home然后你写:
rm -rf ./"$basedirectory"/
回答by anubhava
To get the first firectory:
要获得第一个烟火:
path=/home/user/example/foo/bar
mkdir -p "/tmp/backup$path"
cd /tmp/backup
arr=( */ )
echo "${arr[0]}"
PS: Never use PATH variable in your script as it will overrider default PATH and you script won't be able to execute many system utilities
PS:切勿在脚本中使用 PATH 变量,因为它会覆盖默认 PATH 并且您的脚本将无法执行许多系统实用程序
EDIT:Probably this should work for you:
编辑:这可能对你有用:
IFS=/ && set -- $path; echo ""
home
回答by Thomazella
Pure bash:
纯猛击:
DIR="/home/user/example/foo/bar"
[[ "$DIR" =~ ^[/][^/]+ ]] && printf "$BASH_REMATCH"
Easy to tweak the regex.
易于调整正则表达式。