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.

shell 获取 目录名 当前目录名的更多相关文章

  1. shell 提取文件名和目录名

    转自http://blog.csdn.net/universe_hao/article/details/52640321 shell 提取文件名和目录名 在写shell脚本中,经常会有需要对路径和文件 ...

  2. Bash Shell 获取进程 PID

    转载地址:http://weyo.me/pages/techs/linux-get-pid/ 导读 Linux 的交互式 Shell 与 Shell 脚本存在一定的差异,主要是由于后者存在一个独立的运 ...

  3. 用C++和shell获取本机CPU、网卡IO、内存、磁盘等的基本信息

    用C++和shell获取本机CPU.网卡.内存.磁盘等的基本信息: 由于对C++相关的函数没多少了解,但是觉得用shell反而相对简单一些: 一.shell脚本,用来辅助C++获取主机的资源使用信息 ...

  4. linux中用shell获取昨天、明天或多天前的日期

    linux中用shell获取昨天.明天或多天前的日期 时间 -- :: BlogJava-专家区 原文 http://www.blogjava.net/xzclog/archive/2015/12/0 ...

  5. linux中用shell获取时间,日期

    linux中用shell获取昨天.明天或多天前的日期:在Linux中对man date -d 参数说的比较模糊,以下举例进一步说明:# -d, --date=STRING display time d ...

  6. shell 获取网关 以及修改ip 启用网卡

    shell 获取网关 以及修改ip 启用网卡 #!/bin/bash #autho freefei #script is a init computer eth #data 2014 10 09 19 ...

  7. python执行shell获取硬件参数写入mysql

    最近要获取服务器各种参数,包括cpu.内存.磁盘.型号等信息.试用了Hyperic HQ.Nagios和Snmp,它们功能都挺强大的,但是于需求不是太符,亦或者太heavy. 于是乎想到用python ...

  8. Shell获取格式化日期

    Shell获取格式化日期 shell date 获取昨天日期 使用date -d 选项: date +"%Y%m%d" -d "+n days" 今天的后n天日 ...

  9. Shell获取文件的文件名和扩展名的例子

    这篇文章主要介绍了Shell获取文件的文件名和扩展名的例子,简明版的代码实例,看了就懂,需要的朋友可以参考下 basename example.tar.gz .tar.gz # => examp ...

  10. linux命令(26):Bash Shell 获取进程 PID

    转载地址:http://weyo.me/pages/techs/linux-get-pid/ 根据pid,kill该进程:http://www.cnblogs.com/lovychen/p/54113 ...

随机推荐

  1. 关于BarchNorm的一些学习

    <Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift> ...

  2. 66.有没有碰到过数组响应丢失(问的是ref和reactive的用法,什么情况下用)

    由于vue3使用proxy,对于对象和数组都不能直接整个赋值.  直接赋值丢失了响应性 只有push或者根据索引遍历赋值才可以保留reactive数组的响应性  : 可以使用 toRefs 解决这个问 ...

  3. 比赛题解 更新ING

    CF Codeforces Round #750 (Div. 2) (水题.组合数学.双指针+搜索.构造.dp.dp) Codeforces Round #747 (Div. 2) (水题.水题.埃筛 ...

  4. 如果读完这几百 Python 的书籍,能成编程大佬吗? #Python 入门 #编程 #编程学习 #知识分享

  5. 痞子衡嵌入式:瑞萨RA系列FSP固件库分析之外设驱动

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是瑞萨RA系列FSP固件库里的外设驱动. 上一篇文章 <瑞萨RA8系列高性能MCU开发初体验>,痞子衡带大家快速体验了一下瑞萨 ...

  6. java CAS及各种锁

    CAS CAS 缺点:循环会耗时:一次性只能保持一个共享变量的原子性:ABA问题 package juc.cas; import java.util.concurrent.atomic.AtomicI ...

  7. git知识点,常用命令

    git理论知识 git的服务器端(remote)端包含多个repository,每个repository可以理解为一个项目. 而每个repository下有多个branch."origin& ...

  8. hbase的架构

    HBase中的存储包括HMaster.HRegionSever.HRegion.HLog.Store.MemStore.StoreFile.HFile等角色构成,具体如下HMaster的作用 1.为H ...

  9. php在大并发下redis锁实现

    在现如今电商盛行的时期,会出现很多促销活动,最为常见的就是秒杀.在秒杀系统中最为常见的问题就是会出现超卖的情况,那么如何来杜绝超卖的情形了,在业务逻辑层面可以使用缓存以及加锁的手法来避免超卖的情形. ...

  10. 海外模组联网难?那你必须看看APN配置…

    ​做海外的设备,如果忽视了射频的信号质量,肯定是要吃大亏的! 因为国外的4G信号都是比较差的! 所以,海外模组的联网问题,会比国内要多不少. 客户在实际应用中或多或少都会遇到: 网络相关问题:例如:连 ...