2.beginning bash 《bashcookbook》

1.4 获取文件信息
Problem

你需要获得更多的文件信息,比如它是什么?拥有者是谁,是否可以执行,有多少个链接指向这个文件,最后的修改时间是什么时候.
Solution

使用ls,stat,file,find,touch命令.
delbert@delbert-desktop:~$ ll myinitlog
rw-rw-rw 1 delbert delbert 3896 2009-07-09 09:46 myinitlog
delbert@delbert-desktop:~$ touch myinitlog
delbert@delbert-desktop:~$ ll myinitlog
rw-rw-rw 1 delbert delbert 3896 2009-07-09 17:33 myinitlog

$ ls /tmp/sample_file
/tmp/sample_file
$ ls -l /tmp/sample_file
rw-rr- 1 jp jp 0 Dec 18 15:03 /tmp/sample_file
$ stat /tmp/sample_file
File: "/tmp/sample_file"
Size: 0 Blocks: 0 IO Block: 4096 Regular File
Device: 303h/771d Inode: 2310201 Links: 1
Access: (0644/rw-rr-) Uid: ( 501/ jp) Gid: ( 501/ jp)
Access: Sun Dec 18 15:03:35 2005
Modify: Sun Dec 18 15:03:35 2005
Change: Sun Dec 18 15:03:42 2005
$ file /tmp/sample_file
/tmp/sample_file: empty
$ file -b /tmp/sample_file
empty
$ echo '#!/bin/bash -' > /tmp/sample_file
$ file /tmp/sample_file
/tmp/sample_file: Bourne-Again shell script text executable
$ file -b /tmp/sample_file
Bourne-Again shell script text executable
Discusstion
1.5 在当前目录显示所有隐藏文件
Problem

有一个创建了很久的文件,当我们需要再次编辑或者删除它时,可能我们会忘记这个文件的具体名称,通过ls -a我们可以查看当前
目录下的所有文件包括隐藏文件,但是通常显示的结果让我们眼花缭乱,而使用ls -a .*并不能得到我们想要的结果(试试看).
Solution

使用ls -d(pattern) ,可以添加过滤条件.比如:
ls -d .*
ls -d .b*
ls -d .!.*
另外的方式:
$ grep -l 'PATH' ~/.!.*
/home/jp/.bash_history
/home/jp/.bash_profile
1.6 在shell中使用引号
Problem

你需要一本在shell中使用引号的经验手册。
Solution

使用单引号包含一段字符串,除非字符串里有需要shell解析的元素。
Discusstion

未被引号包含或者使用双引号包含的字符串需要依赖shell的扩展和替换。看看:
$ echo A coffee is $5?!
A coffee is ?!
$ echo "A coffee is $5?!"
-bash: !": event not found
$ echo 'A coffee is $5?!'
A coffee is $5?!
第一个例子,$5被shell作为变量展开,但是这个变量不存在,所以显示为空
第二个例子也是一样的,只是我们得不到正确结果,因为!"被理解为执行某个
历史命令的表达式,但是这个表达式在历史命令中找不到。
第三个我们得到了希望的结果。

如果需要混合shell扩展表达式和仅按字面意义表达的字符串你可以使用转义字符\
或者替换引号类型,感叹号是一个特殊的例子因为在显示时\ 并不会被移除。你可以
用单引号包含感叹号或者不转义但是在感叹号后使用空格来正确显示。

$ echo 'A coffee is $5 for' "$USER" '?!'
A coffee is $5 for jp ?!
$ echo "A coffee is \$5 for $USER?!"
A coffee is $5 for jp?!
$ echo "A coffee is \$5 for $USER?! "
A coffee is $5 for jp?!

类似的,你不能嵌入一个单引号到一对单引号中,即使你使用了转义字符,因为使用
单引号包含时,没有任何东西会被扩展或替换,但是你可以使用双引号加转义字符,或者
在成对单引号的外部使用转义字符来显示单引号。

1. We'll get a continuation prompt since we now have unbalanced quotes
$ echo '$USER won't pay $5 for coffee.'
> ^C
2. WRONG
$ echo "$USER won't pay $5 for coffee."
jp won't pay for coffee.
3. Works
$ echo "$USER won't pay \$5 for coffee."
jp won't pay $5 for coffee.
4. Also works
$ echo 'I won'\''t pay $5 for coffee.'
I won't pay $5 for coffee.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值