由于需要在mac做大量的文件操作,所以自学下shell脚本,随便做下笔记。
1.新建一个shell文件
我是用Sublime的,蛮好用的,第一个当然是"helloWorld"。
#!/bin/sh
echo helloWorld
保存,后缀名改为.sh。可以将文件拖动终端运行。
注意:如果运行时提示权限不足时,可以使用chmod +x *.sh 来运行。
1.遍历文件夹
#!/bin/sh
deepls() {
cd "$1"
for x in *
do
if [ -f $x ]; then
echo $x
fi
if [ -d $x ]
then
(deepls "$PWD/$x")
fi
done
}
deepls $PWD
-f 判断x是否为文件
-d 判断x是否为文件夹
2.删除文件
rm -rf $x
这个指令要谨慎使用,我常常误删文件,而且很难恢复。
3.重命名文件
mv "oldname" "newname"
4.拷贝文件
cp "src/file" "newsrc/file"
5.字符串处理
1)截取字符串
${变量名:起始:长度}得到子字符串
${test##*/},${test%/*} 分别是得到文件名,目录地址最简单方法。
2)字符串长度
${#变量名}得到字符串长度
字符串判断
str1 = str2当两个字符串有相同内容、长度时为真
str1 != str2当字符串str1和str2不等时为真
str1 =~ str2当字符串str1含有str2时为真
-n str1
当串的长度大于0时为真(串非空)
-z str1 当串的长度为0时为真(空串)
str1 当串str1为非空时为真
-z str1 当串的长度为0时为真(空串)
str1 当串str1为非空时为真
逻辑判断
-a与
-o或
!非
附加一些有用的指令
强制 Finder 程序显示隐藏文件
defaults write com.apple.finder AppleShowAllFiles TRUE
强制 Finder 程序不显示隐藏文件
defaults write com.apple.finder AppleShowAllFiles FALSE
touch test.txt