shell 获取 目录名 当前目录名

本文介绍在Shell脚本编程中如何仅提取当前工作目录的名称,而非完整的路径信息。通过使用basename命令、参数替换、awk与rev的组合以及sed命令等四种方式,文章详细解释了每种方法的具体实现过程。

Four ways to extract the current directory name

By  Sergio Gonzalez Duran on November 06, 2007 (9:00:00 AM)   

When you're programming a shell script, you often only need the current directory name, not the whole path that the pwd command returns. Here are four ways you can extract only the current directory.

Using basename

Using the basename command is the easiest and simplest way to extract the current directory:

basename /usr/local/bin
bin

However, it isn't useful in a shell script with changing directory variables. You can combine it with pwd inside backticks to make it more dynamic:

cd /usr/local/bin
basename `pwd`
bin
Using parameter substitution with echo

The bash scripting language is full of nice tricks, including parameter substitution, which allows you to manipulate or expand variables. You can use parameter substitution with the${var##pattern} syntax, which removes from $var the longest part of $Pattern that matches the front end of $var. Take a look at an example:

cd /var/log/squid
echo ${PWD##*/}
squid

PWD is the environment variable that holds the current path, and ## is the instruction that tells the script to remove everything it finds up to */. In other words, it removes everything until the last /, leaving only the last string, which here is the current directory, squid. You can learn more about parameter substitution and other ways to manipulate variables in the Advanced Bash-Scripting Guide.

Using awk and rev

A more elaborate solution uses a combination of awk (a pattern-scanning utility) and rev (a utility that reverses lines from a file or from stdin):

cd /usr/share/cups/data
pwd | rev | awk –F \/ '{print $1}' | rev
data

It's a lot easier to understand this kind of script step by step:

pwd
/usr/share/cups/data
pwd | rev 
atad/supc/erahs/rsu/
pwd | rev | awk –F \/ '{print $1}'
atad
pwd | rev | awk –F \/ '{print $1}' | rev
data

The -F option indicates that you should separate by fields, where the field delimiter is /, and that you should print field 1.

Using sed

Finally, you can parse pwd output in the stream editor sed using an elaborate regular expression. This approach may be educational, but it's not practical:

cd /home/smith/music
pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'
music

For a better understanding of how this works, remove the escape character (\), which is required for special characters such as "(":

sed 's,^(.*/)?([^/]*),\2,'

s substitutes one string for another. It looks for two patterns, which are indicated between the first comma and the second comma. The first pattern (^(.*/)?) searches from the beginning of the line (^) until the last occurrence that it finds of / (in the example, it matches /home/smith/). The second pattern (([^/]*)) searches everything from the last pattern except the / character , which is indicated by [^/]*, where ^ at the beginning of the square brackets means not. This results in both /home/smith/ and music. The second part of this regular expression is the substitution, indicated by \2. In sed, this is called a back reference. As its name implies, it goes back and recalls a previously used reference. There may be nine of these, named \1, \2, \3, and so on. In the example, \2 refers to the second pattern found, which is music -- the result expected.

As you can see, Linux gives you many ways to find a directory name. Having many choices for the same chore is one of its strengths.

Sergio Gonzalez Duran is a Linux administrator, systems developer, and network security counselor who also teaches Linux courses and publishes the Spanish-oriented Linux and open source Web site linuxtotal.com.mx.

<think>首先,用户的问题是:“我想查找在shell获取上级目录的方法 请问shell获取上级目录的方法”。意思是用户想在shell脚本中获取上级目录的方法。 我需要参考用户提供的引用: - 引用[1]讨论了使用pwd获取当前目录,并提到了一个脚本片段:workdir=$(cd $(dirname $0); pwd) 用于获取当前脚本的父目录。还提到了一个更复杂的方法来获取脚本文件的父目录。 - 引用[2]是关于获取目录大小的,但提到了du命令,与获取上级目录无关。 - 引用[3]详细描述了如何获取上级目录的方法:使用${var##*/}来获取目录名,使用awk和rev,或使用sed。具体例子:echo ${PWD##*/} 获取当前目录名,但这不是上级目录。 引用[3]说:要获得目录名,可以:cd /var/log/squid echo ${PWD##*/} 输出 squid。这是获取当前目录名,不是上级目录。 然后它说:使用dirname命令。在引用[3]中提到:使用dirname:echo $(dirname "$PWD") 获取上级目录。在引用[4]中更清晰。 - 引用[4]明确说:echo $(dirname "$PWD") 的输出是上级目录。例如:在/home/test/test1,echo $(dirname "$PWD") 输出 /home/test。 关键点:获取上级目录的方法是使用dirname命令。 从引用中提取: - 使用dirname命令:dirname "$PWD" 或类似。 具体方法: 1. 使用dirname命令:如果PWD是当前目录,dirname "$PWD" 返回上级目录。 2. 在脚本中,可以使用workdir=$(cd $(dirname $0); pwd) 来获取当前脚本的父目录,但这用于脚本文件,不是一般意义上的当前目录。 用户的查询是“获取上级目录的方法”,不是特定于脚本的。所以,我应该覆盖一般方法。 总结方法: - 要获取当前目录的上级目录,可以使用dirname "$PWD"。 - 也可以使用其他方法如awk或sed,但dirname是最简单和推荐的。 在回答中,我需要: - 使用中文回答(系统指令5)。 - 结构清晰,逐步解决问题。 - 由于是系统级指令,所有行内数学表达式用$...$,但这里可能没有数学,主要是代码块。 - 独立公式用$$...$$,但可能不适用。 - 生成相关问题(系统指令6)。 - 引用中添加引用标识,如[^1]。 回答结构: 1. 介绍问题。 2. 解释方法。 3. 提供代码示例。 4. 添加相关问题。 确保回答真实可靠。 关键方法: - 使用dirname命令:dirname "$PWD" 获取当前工作目录的上级。 - 或者,对于脚本文件,dirname $0 获取脚本所在目录的路径,然后可以获取其上级。 在shell中: - pwd 获取当前目录。 - dirname path 获取路径的上级目录。 所以,要获取当前目录的上级:dirname "$(pwd)" 或直接 dirname "$PWD",因为PWD是环境变量。 在引用[4]中:echo $(dirname "$PWD") 输出上级目录。 在bash脚本中: crtdir=$(pwd) # 当前目录 parent_dir=$(dirname "$crtdir") 或者直接: parent_dir=$(dirname "$PWD") 另一个方法是从路径中解析。 但我应该推荐dirname作为标准方法。 提供简单示例。 回答结构: - 先说:在shell获取上级目录的常见方法是使用dirname命令。 - 解释:dirname命令可以获取给定路径的上级目录。 - 例如:如果当前目录是/home/test,那么dirname /home/test 输出 /home。 - 在脚本中,可以使用dirname "$PWD" 来获取上级目录。 - 代码示例: #!/bin/bash current_dir=$(pwd) parent_dir=$(dirname "$current_dir") echo "当前目录: $current_dir" echo "上级目录: $parent_dir" 更简洁:parent_dir=$(dirname "$PWD") - 也可以使用其他方法,如basename和dirname组合,但dirname是直接的。 生成相关问题: 1. 如何在shell获取脚本所在的目录? 2. 如何使用dirname和basename命令操作路径? 3. 在shell中如何获取更上层的目录? 添加引用:基于引用[4]。 在末尾添加引用标识,如[^4]。 系统指令说:回答中引用的段落末尾自然地添加引用标识。 在我的回答中,当提到方法时,添加引用。 例如:使用dirname命令可以方便地获取上级目录,如例所示[^4]。 相关问题: §§相关问题§§ 1. shell中如何获取当前目录的名称? 2. 如何在shell获取脚本文件的完整路径? 3. 在shell中如何递归获取目录大小? </think>### shell获取上级目录的方法 在shell脚本中,获取当前目录的上级目录(也称为父目录)是一个常见需求,通常用于路径操作或脚本配置。实现这一目标的最简单、最标准的方法是使用 `dirname` 命令,它可以直接返回给定路径的上级目录路径。下面我将逐步解释方法、提供代码示例,并基于您的引用内容确保回答可靠。核心思路是:先获取当前目录(例如使用 `pwd` 或环境变量 `$PWD`),然后通过 `dirname` 命令提取其上级目录。 #### 步骤说明 1. **获取当前目录**:使用 `pwd` 命令(print working directory)或环境变量 `$PWD` 获取当前目录的完整路径。 2. **提取上级目录**:将当前目录路径传递给 `dirname` 命令,它会移除路径的最后一个部分(即当前目录名),返回上级目录路径。 3. **处理特殊情况**:如果当前目录是根目录(如 `/`),`dirname` 会返回 `/`(因为根目录没有上级);如果路径中包含符号链接,可能需要额外处理(参考引用中的复杂方法)。 #### 代码示例 以下示例展示了如何在shell脚本中获取上级目录。我将提供两种常见场景:**一般当前目录**和**脚本文件的父目录**(后者在引用[^1]中提及)。 ##### 示例1:获取当前工作目录的上级目录(最简单方法) ```bash #!/bin/bash # 方法1:直接使用环境变量 $PWD 和 dirname parent_dir=$(dirname "$PWD") echo "当前目录: $PWD" echo "上级目录: $parent_dir" ``` - **解释**: - `$PWD` 存储当前目录的完整路径(如 `/home/test/test1`)。 - `dirname "$PWD"` 提取上级目录(如 `/home/test`)。 - 这种方法高效且可读性强,是推荐的标准方式[^4]。 ##### 示例2:获取脚本文件所在目录的上级目录(适用于脚本) 如果您的脚本需要获取自身所在目录的上级目录(例如脚本位于 `/path/to/script.sh`),可以使用 `dirname $0` 获取脚本目录,然后提取上级目录。这在引用[^1]中提到过(`workdir=$(cd $(dirname $0); pwd)` 获取脚本父目录)。 ```bash #!/bin/bash # 方法2:获取脚本文件的上级目录 script_dir=$(dirname "$(realpath "$0")") # 使用 realpath 处理符号链接 parent_of_script_dir=$(dirname "$script_dir") echo "脚本所在目录: $script_dir" echo "脚本的上级目录: $parent_of_script_dir" ``` - **解释**: - `$0` 表示脚本文件名。 - `realpath "$0"` 获取脚本的绝对路径(避免符号链接问题)。 - `dirname` 用于逐步提取上级目录。 - 这种方法在部署脚本时常用,确保路径准确性[^1]。 ##### 其他方法(备选) 虽然 `dirname` 是首选,但引用[^3]提供了替代方案(如使用 `awk` 或 `sed`),适用于高级场景。例如: ```bash # 使用 awk 获取上级目录(基于引用[^3]) parent_dir=$(echo "$PWD" | awk -F'/' 'BEGIN{OFS="/"}{$NF=""; print $0}' | sed 's/\/$//') echo "上级目录(awk方法): $parent_dir" ``` - **解释**:这个命令将路径按 `/` 分割,移除最后一部分后重组。但 `dirname` 更简洁,建议仅在需要复杂路径处理时使用此方法[^3]。 #### 注意事项 - **符号链接的处理**:如果路径涉及符号链接,使用 `realpath` 命令(如示例2)可以解析真实路径,避免错误。 - **性能**:`dirname` 命令是内置的(在大多数shell中),执行速度快,适合脚本。 - **错误处理**:在脚本中添加检查(如 `if [ -d "$parent_dir" ]; then ... fi`)确保目录存在。 - **跨平台兼容性**:这些方法适用于bash、sh等常见shell(Linux/macOS)。 通过以上方法,您可以轻松在shell获取上级目录。如果需要递归获取更上层的目录(如上级的上级),可以多次调用 `dirname`(例如 `dirname "$(dirname "$PWD")"`)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值