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. Android dtbo(1) dto简介

    设备树 (DT, Device Tree) 是用于描述 non-discoverable(google这样写的,意思应该就是硬件信息看不到) 硬件的命名节点和属性构成的一种数据结构.操作系统(例如在 ...

  2. argmax经过sigmoid和不经过sigmoid区别

    起因 今天和同组讨论了一下网络输出时,在torch.argmax之前经过torch.sigmoid和不经过sigmoid的区别. 主要起因是实验结果图像不同 图1 不经过sigmoid 图2 经过si ...

  3. Java实用小工具系列2---使用StopWatch统计多个任务耗时分布

    在Java中经常需要统计程序的使用时间,如果只是一个时间段统计比较好处理,可以直接使用System.currentTimeMillis().但如果一个程序中包含多个步骤,需要统计每个步骤耗时,并且需要 ...

  4. vue2基于 vue-cropper插件对图片裁剪

    <template> <div id="app"> <div class="model" v-show="model&q ...

  5. 11 Self-Attention相比较 RNN和LSTM的优缺点

    博客配套视频链接: https://space.bilibili.com/383551518?spm_id_from=333.1007.0.0 b 站直接看 配套 github 链接:https:// ...

  6. java截取##间的话题字符串

    转载MARK一下,百度根据关键字不好搜到,省的下次到处找.package iqiyi.com.model;import java.util.regex.Matcher;import java.util ...

  7. 基础控件(Button,Edittext,ImageView,ProgressBar,ToolBar,AlertDialog,PopupWindow)

    Button 触发事件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: ...

  8. 2022/1/25-2022牛客寒假算法基础集训营1B-炸鸡块君与FIFA22(线段树)

    题目描述 热爱足球(仅限游戏)的炸鸡块君最近购买了FIFA22,并且沉迷于FIFA22的Rivals排位上分. 在该排位系统中,每局游戏可能有胜利(用W表示).失败(用L表示).平局(用D表示)三种结 ...

  9. 腾讯AICR : 智能化代码评审技术探索与应用实践(下)

  10. kafka之介绍

    Kafka 由于高吞吐量.可持久化.分布式.支持流数据处理等特性而被广泛应用.但当前关于Kafka原理及应用的相关资料较少,在我打算编写本文时,还没有见到中文版本的Kafka相关书籍,对于初学者甚至是 ...