Shell常用操作记录

  • 修改 Linux 系统 Shell 的编码
1
2
3
export LANG="en_US.UTF-8"
export LANG="zh_CN.GBK"
export LANG="zh_CN.UTF-8"
  • 在 Java 代码里面执行 Shell 命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 执行系统命令, 返回执行结果
* @param cmd 需要执行的命令
* @param dir 执行命令的子进程的工作目录, null 表示和当前主进程工作目录相同
*/
public static String execCmd(String cmd, File dir) {

StringBuilder result = new StringBuilder();

Process process = null;
BufferedReader bufrIn = null;
BufferedReader bufrError = null;

try {
String[] commond = {"/bin/sh", "-c", cmd};
// 执行命令, 返回一个子进程对象(命令在子进程中执行)
process = Runtime.getRuntime().exec(commond, null, dir);

// 方法阻塞, 等待命令执行完成(成功会返回0)
process.waitFor();

// 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入)
bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));

// 读取输出
String line = null;
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
}
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
}

} catch (Exception e) {
logger.error(e);
} finally {
closeStream(bufrIn);
closeStream(bufrError);

// 销毁子进程
if (process != null) {
process.destroy();
}
}

// 返回执行结果
return result.toString();
}

private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
// nothing
}
}
}
  • Shell 中 Map 的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 定义一个空map        
declare -A map=()
# 定义并初始化map        
declare -A map=(["100"]="1" ["200"]="2")
# 输出所有key
echo ${!map[@]}
# 输出所有value        
echo ${map[@]}
# 添加值
map["300"]="3"
# 输出key对应的值
echo ${map["100"]}
# 遍历输出map
for key in ${!map[@]}
do
echo ${map[$key]}
done

在 Mac 环境中会出错,因为 Mac OS X 的默认Bash 是 3.x 版本,不支持 map 这种数据结构,
有两种解决方案:

  1. 升级bash到 4.x 以上版本
  2. 用其他方式:比如 if elif 去到达相同的结果
  • tcpdump的使用
1
sudo tcpdump -i lo0 dst host 127.0.0.1 and port 8080
  • netstat的使用
1
netstat -n -p tcp | grep 8080
  • 统计当前文件夹下文件的个数
1
ls -l | grep "^-" | wc -l
  • 统计当前文件夹下目录的个数
1
ls -l | grep "^d" | wc -l
  • 统计当前文件夹下文件的个数,包括子文件夹里的
1
ls -lR | grep "^-" | wc -l
  • 统计文件夹下目录的个数,包括子文件夹里的
1
ls -lR | grep "^d" | wc -l