Shell Commands

  1. basename/dirname/export/PWD
basename
从文件名中去掉路径信息, 只打印出文件名. 结构 basename $0 可以让脚本知道它自己的名字, 也就是, 它被调用的名字. 可以用来显示用法信息, 比如如果你调用脚本的时候缺少参数, 可以使用如下语句:
echo "Usage: `basename $0` arg1 arg2 ... argn"   dirname
从带路径的文件名中去掉文件名, 只打印出路径信息.   basenamedirname 可以操作任意字符串. 参数可以不是一个真正存在的文件, 甚至可以不是一个文件名  
export命令
可以将一个局部变量提供给Shell执行的其他命令使用,其格式为: export 变量名
也可以在给变量赋值的同时使用export命令: export 变量名=变量值
使用export说明的变量,在Shell以后运行的所有命令或程序中都可以访问到。

PWD
当前工作目录的绝对路径名,该变量的取值随cd命令的使用而变化

 

  1. shell获取当前目录名的几种方法

1.basename

 

basename `pwd`

2.echo

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:

 

echo ${PWD##*/}

3.awk

 

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.

4.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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值