Skip to content

Bash常用命令清单

jiaxw32 edited this page Jun 10, 2021 · 6 revisions

获取指定目录的上一级目录

dir=/Users/jiaxw/Workspace
parentdir="$(dirname "$dir")"

获取当前目录的上一级目录

parentdir=$(dirname `pwd`)

按文件大小排序

  • find 命令
# 按文件大小升序
find . -type f -exec ls -l {} \; | sort -k 5 -n
# 按文件大小降序
find . -type f -exec ls -l {} \; | sort -k 5 -rn
  • ls 命令
# S 按文件大小排序,R 递归子目录
ls -lSR | sort -k 5 -n
# 使用 h 参数,增强文件大小易读性
ls -lSR | sort -k 5 -n

ls 命令

h 参数

-l 参数一起使用,使用字节(B)、千字节(KB)、兆(M)等作为文件大小后缀,增加易读性。

ls -lh

t 参数

按文件修改时间排序,最新修改的优先显示

# 降序排列,最新修改的优先显示
ls -lt
# 升序排列,最新修改的最后显示
ls -ltr

find 命令

-name 参数组合

示例1:

find . -type f  \( -name "*.h" -o -name "*.m" -o -name "*.mm" \)

示例2:

find /media/d/ -type f -size +50M ! \( -name "*deb" -o -name "*vmdk" \)
  • ! expression : Negation of a primary; the unary NOT operator.

  • ( expression ): True if expression is true.

  • expression -o expression: Alternation of primaries; the OR operator. The second expression shall not be evaluated if the first expression is true.

Note that parenthesis, both opening and closing, are prefixed by a backslash () to prevent evaluation by the shell.

find-exec 组合使用示例

  • 查找当前目录下的所有文件,并输出
find . -type f -exec echo {} \;
  • 找出当前目录下所有root的文件,并把所有权更改为用户tom
find .-type f -user root -exec chown tom {} \;

{} 用于与-exec选项结合使用来匹配所有文件,然后会被替换为相应的文件名。

  • 找出当前目录下所有的.txt文件并删除
find . -name "*.txt" -ok rm {} \;

-ok和-exec行为一样,不过它会给出提示,是否执行相应的操作。

  • 查找当前目录下所有.txt文件并把他们拼接起来写入到all.txt文件中
find . -type f -name "*.txt" -exec cat {} \;> all.txt
  • 将30天前的.log文件移动到old目录中
find . -type f -mtime +30 -name "*.log" -exec cp {} old \;

date 命令

示例1:

# 获取当前时间
date=$(date '+%Y-%m-%d %H:%M:%S')

示例 2

date "+DATE: %Y-%m-%d%nTIME: %H:%M:%S"

输出结果如下:

DATE: 1987-11-21
TIME: 13:36:16
  • %Y is replaced by the year with century as a decimal number.
  • %m is replaced by the month as a decimal number (01-12).
  • %d is replaced by the day of the month as a decimal number (01-31).
  • %H is replaced by the hour (24-hour clock) as a decimal number (00-23).
  • %M is replaced by the minute as a decimal number (00-59).
  • %S is replaced by the second as a decimal number (00-60).

An operand with a leading plus (+) sign signals a user-defined format string which specifies the format in which to display the date and time. The format string may contain any of the conversion specifications described in the strftime(3) manual page. The format string for the default display is +%+.

获取指定命令路径

type -a ls
ls is an alias for ls -G
ls is /bin/ls

➜ type -a which
which is a shell builtin
which is /usr/bin/which

This will show whether the command is a builtin, a function, an alias or an external executable. If the latter, it will show each place it appears in your PATH.

参考资料

Clone this wiki locally