前言

自用的shell脚本,现学现用,也许不是那么规范,权当自己的学习笔记,老鸟莫笑。

基础语法

判断命令是否存在:

1
2
3
if [ `command -v command` ]; then
# body
fi

判断文件夹是否存在:

1
2
3
if [ ! -d "$directory" ]; then
echo directory is not exists
fi

判断路径是否存在:

1
2
3
if [ -e "$path" ]; then
echo exists
fi

判断文件是否存在:

1
2
3
if [ -f "$file" ]; then
echo file exists
fi

判断文件是否为空:

1
2
3
if [ -s "$file" ]; then
echo file not empty
fi

创建文件夹

文件和文件夹判断语法见上文,判断语句只是参数和创建命令不同,相应变更即可,此处只是示例。如果文件夹 testdir 不存在,则创建:

1
2
3
4
5
6
7
!/bin/bash

if [ ! -d testdir ];then
mkdir testdir
else
echo "dir is exist"
fi

将shell改进一下,接收外部参数直接创建目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
# 判断传入的参数的个数是不是一个
if [ ! $# -eq 1 ];then
echo "param error!"
exit 1
fi

# 判断目录是不是已经存在,如果不存在则创建,存在则输出“dir is exist”
dirname=$1
echo "the dir name is $dirname"
if [ ! -d $dirname ];then
mkdir $dirname
else
echo "dir is exist"
fi

其他应用可以以基础语法举一反三即可。