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. /proc/zoneinfo

    root@pita2_mr813_tina35:/# cat /proc/zoneinfo Node 0, zone DMA per-node stats nr_inactive_anon 4749 ...

  2. 标准库之 random 模块

    一.介绍random模块 1.1.random模块简介 random模块是Python标准库中用于生成伪随机数的模块,伪随机数是通过算法生成的数列,在一定范围内表现出随机性,虽然这些数列在一定程度上是 ...

  3. FFmpeg开发笔记(五十五)寒冬里的安卓程序员可进阶修炼的几种姿势

    ​喊了多年的互联网寒冬,今年的寒风格外凛冽,还在坚守安卓开发的朋友着实不容易.因为能转行的早就转了,能转岗的也早就转了,那么安卓程序员比较迷茫的就是,我该学什么安卓技术才好呢?还是直接扔了安卓再去搞别 ...

  4. BUUCTF BUU SQL COURSE 1

    方法一:手工注入 启动靶机 寻找注入点,使用burp抓包得到传参页面 得到注入点 /backend/content_detail.php?id=1 用and 1 =1 和 and 1 =2 判断存在s ...

  5. 牛逼!5K star! 推荐一款集监控和埋点于一体的前端性能监控工具!开源、简单易用、功能强大!

    在互联网的快速发展下,网站已成为企业和个人展示信息.提供服务的重要平台.然而,随之而来的网站性能问题也日益凸显,如加载速度慢.频繁出错.服务器故障.数据异常.网络攻击等.如何确保用户能够快速稳定地访问 ...

  6. SpringBoot读取properties文件配置项

    使用SpringBoot开发过程中,难免需要配置相关数据项,然后在Java代码中@Autowired注入并使用. 我们应该如何读取properties文件中的配置项呢? 基于SpringBoot项目, ...

  7. 鸿蒙NEXT应用上架与分发步骤详解

    大家好,我是 V 哥.今天的文章来聊一聊HarmonyOS NEXT应用上架.当你开发.调试完HarmonyOS应用/元服务,就可以前往AppGallery Connect申请上架,华为审核通过后,用 ...

  8. Java面试题中高级进阶(JVM篇Java内存)

    前言 本来想着给自己放松一下,刷刷博客,突然被几道面试题难倒!说说Java内存结构?说说对象分配规则?描述一下JVM加载class文件的原理机制?似乎有点模糊了,那就大概看一下面试题吧.好记性不如烂键 ...

  9. selenium3环境搭建,Firefox与对应的geckodriver, chrome与对应的Chromedriver

    Firefox与对应的geckodriver 火狐下载:http://ftp.mozilla.org/pub/firefox/releases/ geckodriver下载:https://githu ...

  10. git clone失败,超时,速度慢

    最近使用git这个工具,发现git clone指令经常由于网络问题导致失败.查找相关资料之后,找到办法为修改网址,具体为: 将 git clone https://github.com/alibaba ...