Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

Netkiller Shell 手札

Unix, Linux, FreeBSD & Mac Shell

Mr. Neo Chan, 陈景峰(BG7NYT)



中国广东省深圳市望海路半岛城邦三期
518067
+86 13113668890


2009-11-15

电子书最近一次更新于 2026-08-05 15:33:47

版权声明

转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。

http://www.netkiller.cn
http://netkiller.github.io
http://netkiller.sourceforge.net
微信公众号: netkiller
微信:13113668890 请注明“读者”
QQ:13721218 请注明“读者”
QQ群:128659835 请注明“读者”
知乎专栏

内容摘要

Netkiller 系列手札 已经被 Github 收录,并备份保存在北极地下250米深的代码库中,备份会保留1000年。

Preserving open source software for future generations

The world is powered by open source software. It is a hidden cornerstone of modern civilization, and the shared heritage of all humanity.

The GitHub Arctic Code Vault is a data repository preserved in the Arctic World Archive (AWA), a very-long-term archival facility 250 meters deep in the permafrost of an Arctic mountain.

We are collaborating with the Bodleian Library in Oxford, the Bibliotheca Alexandrina in Egypt, and Stanford Libraries in California to store copies of 17,000 of GitHub’s most popular and most-depended-upon projects—open source’s “greatest hits”—in their archives, in museum-quality cases, to preserve them for future generations.

我们正在与牛津的博德利安图书馆、埃及的亚历山大图书馆和加利福尼亚州的斯坦福图书馆合作,将 GitHub 最受欢迎和最依赖的项目 17,000 份副本保存在他们的档案中,在博物馆质量的案例中,为子孙后代保存这些作品。

https://archiveprogram.github.com/arctic-vault/

我的系列文档:

Netkiller Linux 手札 Netkiller FreeBSD 手札 Netkiller Shell 手札 Netkiller Security 手札
Netkiller Web 手札 Netkiller Monitoring 手札 Netkiller Storage 手札 Netkiller Mail 手札
Netkiller Virtualization 手札 Netkiller Cryptography 手札   

以下文档停止更新合并到 《Netkiller Linux 手札》

Netkiller Debian 手札 Netkiller CentOS 手札 Netkiller Multimedia 手札    

致读者

Netkiller 系列手札 已经被 Github 收录,并备份保存在北极地下250米深的代码库中,备份会保留1000年。

Preserving open source software for future generations

The world is powered by open source software. It is a hidden cornerstone of modern civilization, and the shared heritage of all humanity.

The GitHub Arctic Code Vault is a data repository preserved in the Arctic World Archive (AWA), a very-long-term archival facility 250 meters deep in the permafrost of an Arctic mountain.

We are collaborating with the Bodleian Library in Oxford, the Bibliotheca Alexandrina in Egypt, and Stanford Libraries in California to store copies of 17,000 of GitHub’s most popular and most-depended-upon projects—open source’s “greatest hits”—in their archives, in museum-quality cases, to preserve them for future generations.

https://archiveprogram.github.com/arctic-vault/

目录

1. 自述
1.1. 写给读者
1.2. 作者简介
1.3. 如何获得文档
1.4. 打赏(Donations)
1.5. 联系方式
1. Bash Shell
1.1. bash - GNU Bourne-Again SHell
1.1.1. -n 检查脚本是否有语法错误
1.1.2. -x 显示详细运行过程
1.2. 切换身份
1.3. I/O 重定向
1.3.1. stdout
1.3.2. error 重定向
1.3.3. 使用块记录日志
1.3.4. test - 条件判断命令
1.3.5. tee - read from standard input and write to standard output and files
1.3.6. 创建文件
1.3.7. 快速清空一个文件的内容
1.4. pipes (FIFOs)
1.5. mktemp - create a temporary file or directory 临时目录与文件
1.6. History 命令历史记录
1.6.1. .bash_history
1.6.2. 清理历史记录
1.6.3. .mysql_history
1.7. hash - hash database access method
1.8. prompt
1.9. 变量 variable
1.9.1. 系统变量
1.9.2. 表达式
1.9.3. Internal Environment Variables
1.9.4. set 设置变量
1.9.5. unset 变量销毁
1.9.6. 设置变量默认值
1.9.7. export 设置全局变量
1.9.8. declare
1.9.9. Numerical 数值运算
1.9.10. Strings 字符串操作
1.9.11. Array 数组
1.9.12. read 赋值多个变量
1.9.13. eval
1.9.14. typeset
1.9.15. envsubst - substitutes environment variables in shell format strings
1.10. conditions if and case
1.10.1. if
1.10.2. case
1.11. Loops for, while and until
1.11.1. for
1.11.2. while
1.11.3. until
1.12. Functions
1.12.1. Local variables
1.13. User interfaces
1.13.1. input
1.14. subshell
1.15. Help Commands
1.15.1. man - an interface to the on-line reference manuals
1.16. getconf - Query system configuration variables
1.17. 快捷键
1.17.1. 命令行编辑命令
1.17.2. 重新执行命令快捷键
1.17.3. 终端控制快捷键
1.17.4. Bang (!) 命令
1.18. chsh - change login shell
1.19. 执行程序返回值
1.20. Z Shell
1.20.1. installing Z shell
1.20.2. Oh My ZSH!
1.20.3. Starting file
1.20.4. Prompting
1.20.5. Aliases
1.20.6. History
1.20.7. FAQ
1.21. Berkeley UNIX C shell (csh)
1.21.1.
1.22. KornShell
1.22.1.
1.23. fish shell
1.23.1. 安装 fish shell
1.23.2. 配置 fish
1.23.3. 环境变量
1.24. 有趣的 Shell 应用
1.24.1. Ascii 星球大战电影
1.24.2. 天气预报
1.24.3. htop - interactive process viewer
1.24.4. elinks
1.24.5. chat
1.25. Example
1.25.1. 有趣的Shell
1.25.2. backup
1.25.3. CPU 核心数
1.25.4. Password
1.25.5. processes
1.25.6. Shell 技巧
1.25.7. to convert utf-8 from gb2312 code
1.25.8. 使用内存的百分比
1.25.9. 合并apache被cronlog分割的log文件
1.25.10. Linux 交集 差集 并集
2. 目录和文件
2.1. dirname - 提取目录部分
2.2. basename - 提取文件名部分
2.2.1. 排除扩展名
2.2.2. 取扩展名
2.3. file — determine file type
2.4. stat
2.5. file – determine file type
2.6. mkdir - make directories
2.7. rename
2.8. touch
2.9. truncate
2.10. ls - list directory contents
2.10.1. full-time / time-style 定义日期时间格式
2.11. cp - copy files and directories
2.11.1. copy directories recursively
2.11.2. 覆盖已存在的文件
2.11.3. -a, --archive same as -dR --preserve=all
2.12. rm - remove files or directories
2.12.1. -bash: /bin/rm: Argument list too long
2.12.2. zsh: sure you want to delete all the files in /tmp [yn]?
2.13. df - report file system disk space usage
2.14. du - estimate file space usage
2.15. tac - concatenate and print files in reverse
2.16. split - split a file into pieces
2.16.1. 按行分割文件
2.16.2. 按尺寸分割文件
2.17. find - search for files in a directory hierarchy
2.17.1. 多目录匹配
2.17.2. name
2.17.3. regex
2.17.4. user
2.17.5. perm
2.17.6. type
2.17.7. -delete
2.17.8. exec
2.17.9. 排除目录
2.17.10. -ctime / -cmin - 按状态改变时间查找
2.17.11. -mtime / -mmin - 按修改时间查找
2.17.12. --newer
2.17.13. -print / -printf
2.17.14. -size
2.17.15. -path
2.17.16. 目录深度控制
2.17.17. xargs
2.17.18. 查看空文件
3. 包管理 / 压缩 / 解压
3.1. tar — The GNU version of the tar archiving utility
3.1.1. tar examples
3.1.2. gunzip
3.1.3. b2zip
3.1.4. compress
3.1.5. .xz 文件
3.1.6. -t, --list
3.1.7. tar: Removing leading `/’ from member names
3.1.8. -C, --directory=DIR
3.1.9. --exclude
3.1.10. -T
3.1.11. 日期过滤
3.1.12. 保留权限
3.1.13. -r, --append
3.1.14. 远程传输
3.1.15. 分卷压缩
3.2. cpio - copy files to and from archives
3.3. gzip
3.4. zip, zipcloak, zipnote, zipsplit - package and compress (archive) files
3.5. bzip2, bunzip2 - a block-sorting file compressor
3.6. RAR
3.7. 7-Zip
3.7.1. 压缩
3.7.2. 浏览压缩包
3.7.3. 解压
3.7.4. Creates self extracting archive.
3.8. RAR
3.9. xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files
4. 日期和时间
4.1. 日期格式
4.1.1. weekday name
4.2. -d --date=
4.2.1. 日期偏移量
4.2.2. 时间偏移
4.3. 时间戳
4.4. RFC 2822
4.5. UTC
4.6. 字符串转日期
5. 数值与运算
5.1. 数值运算
5.2. seq - print a sequence of numbers
5.3. bc - An arbitrary precision calculator language
6. 文本处理
6.1. iconv - Convert encoding of given files from one encoding to another
6.1.1. cconv - A iconv based simplified-traditional chinese conversion tool
6.1.2. uconv - convert data from one encoding to another
6.2. 字符串处理命令expr
6.3. cat - concatenate files and print on the standard output
6.3.1. -s, --squeeze-blank suppress repeated empty output lines
6.3.2. -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
6.3.3. 与管道配合使用
6.4. nl - number lines of files
6.5. tr - translate or delete characters
6.5.1. 替换字符
6.5.2. 英文大小写转换
6.5.3. [CHAR*] 和 [CHAR*REPEAT]
6.5.4. -s, --squeeze-repeats replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character
6.5.5. -d, --delete delete characters in SET1, do not translate
6.6. cut - remove sections from each line of files
6.6.1. 字符操作
6.6.2. 列操作
6.7. printf - format and print data
6.8. Free `recode' converts files between various character sets and surfaces.
6.9. /dev/urandom 随机字符串
6.10. col - filter reverse line feeds from input
6.11. apg - generates several random passwords
6.12. head/tail
6.12.1. 彩色输出
6.12.2. 跳过 n 行,输出后面内容
6.12.3. 尾部剪掉 n 行
6.13. 反转字符串或文件内容
6.14. TAB符号与空格处理
6.14.1. expand - convert tabs to spaces
6.14.2. unexpand - convert spaces to tabs
6.15. grep, egrep, fgrep, rgrep - print lines matching a pattern
6.15.1. 删除空行
6.15.2. -v, --invert-match
6.15.3. 输出控制(Output control)
6.15.4. Context control
6.15.5. Regexp selection and interpretation
6.15.6. fgrep
6.15.7. egrep
6.16. sort - sort lines of text files
6.16.1. 对列排序
6.16.2. -s, --stable stabilize sort by disabling last-resort comparison
6.17. uniq
6.18. awk
6.18.1. 处理列
6.18.2. printf
6.18.3. Pattern(字符匹配)
6.18.4. Built-in Variables (NR/NF)
6.18.5. Built-in Functions
6.18.6. 过滤相同的行
6.18.7. 数组演示
6.19. sed
6.19.1. 查找与替换
6.19.2. insert 插入字符
6.19.3. 追加字符
6.19.4. 修改字符
6.19.5. 删除字符
6.19.6. 行操作
6.19.7. 编辑文件
6.19.8. 正则表达式
6.19.9. 管道操作
6.19.10. 字母大小写转换
6.19.11. perl
6.19.12. 案例
6.20. ed, red - text editor
6.21. vim
6.21.1. vim 初始化
6.21.2. 查找与替换
6.21.3. 删除操作
6.21.4. 插入文件
6.21.5. 批处理
6.21.6. line()
6.21.7. set fileformat
6.21.8. 空格与TAB转换
6.22. XML 工具
6.22.1. xmllint - command line XML tool
6.22.2. xmlstarlet - command line XML/XSLT toolkit
6.23. jq - Command-line JSON processor
6.23.1. --raw-output
7. 表格操作/行列转换
7.1. column - columnate lists
7.2. paste - merge lines of files
7.3. join
8. standard input/output
8.1. standard input/output
8.1.1. xargs - build and execute command lines from standard input
8.2. flock - manage locks from shell scripts
9. 进制转换 - 16进制 - 8进制 - 二进制
9.1. od - dump files in octal and other formats
9.1.1. 16进制
9.1.2. 使用 od 随机生成密码
9.2. hexdump, hd -- ASCII, decimal, hexadecimal, octal dump
9.3. xxd - make a hexdump or do the reverse.
9.3.1. 指定每行的列数
9.3.2. 跳过字节
9.4. binutils
9.4.1. strings - print the strings of printable characters in files.
10. 文件比较
10.1. diff
10.2. sdiff
10.3. diff3
11. Wget - The non-interactive network downloader.
11.1. Logging and input file
11.1.1. -i, --input-file=FILE download URLs found in local or external FILE.
11.2. 下载相关参数
11.2.1. -O, --output-document=FILE write documents to FILE 保存到文件
11.3. HTTP options (HTTP 选项)
11.3.1. --post-data=STRING use the POST method; send STRING as the data.
11.3.2. header HTTP头定义
11.4. Recursive download
11.4.1. -r, --recursive specify recursive download.
11.4.2. -m, --mirror shortcut for -N -r -l inf --no-remove-listing.
11.5. --no-passive-ftp disable the "passive" transfer mode.
11.6. 下载一组连续的文件名
12. CURL - transfer a URL
12.1. 基本用法
12.2. 提交表单数据
12.3. 上传文件
12.4. connect-timeout
12.5. max-time
12.6. compressed
12.7. 代理服务器
12.8. -w, --write-out <format> 输出格式定义
12.9. -A/--user-agent <agent string>
12.10. referer
12.11. -v
12.12. -o, --output FILE Write output to <file> instead of stdout
12.13. -L, --location
12.14. -H/--header <line> Custom header to pass to server (H)
12.14.1. Last-Modified / If-Modified-Since
12.14.2. ETag / If-None-Match
12.14.3. Accept-Encoding:gzip,defalte
12.14.4. HOST
12.14.5. HTTP 认证
12.14.6. Accept
12.14.7. Content-Type
12.15. curl-config
12.16. 指定网络接口或者地址
12.17. Cookie 处理
12.18. Restful 应用 JSON 数据处理
12.18.1. Curl Oauth2
12.18.2. Curl + Oauth2 + Jwt
12.19. 访问自签名证书
12.20. HTTP2
12.21. FAQ
13. 信息摘要
13.1. cksum, sum -- display file checksums and block counts
13.2. md5sum - compute and check MD5 message digest
13.3.
14. envsubst - substitutes environment variables in shell format strings
14.1. envsubst - substitutes environment variables in shell format strings
14.2. parallel - build and execute shell command lines from standard input in parallel
14.3. multitail
14.4. Logging
14.4.1. logger - a shell command interface to the syslog(3) system log module
14.5. Password
14.5.1. Shadow password suite configuration.
14.5.2. newusers - update and create new users in batch
14.5.3. chpasswd - update passwords in batch mode
14.5.4. sshpass - noninteractive ssh password provider
15. 常用命令
15.1. 获取IP地址
15.2. 有趣的 Shell 应用
15.2.1. Ascii 星球大战电影
15.2.2. 天气预报
15.2.3. htop - interactive process viewer
15.2.4. elinks
15.2.5. chat
1. 附录
1.1. 参考文献

表格清单

1. Netkiller 系列免费电子书
1.1. 文件目录表达式
1.2. 字符串表达式
1.3. 组合表达式

范例清单

1.1. A "Power User" Prompt
1.2. A Prompt the Width of Your Term
1.3. The Elegant Useless Clock Prompt
1.4. Basic conditional example if .. then
1.5. Conditionals with variables
1.6. case
1.7. Functions with parameters sample
1.8. Using select to make simple menus
1.9. Using the command line
1.10. Reading user input with read
1.11. read
1.12. random password
2.1. 增量备份(find + tar)
2.2. 清理过期日志
2.3. 查找并移动旧文件
2.4. 按时间和大小组合查找
14.1. parallel - build and execute shell command lines from standard input in parallel

1. Shell

1.1. Help Commands

1.1.1. man - an interface to the on-line reference manuals

manpath.config
cat /etc/manpath.config
			
查看man手册位置
$ man -aw ls
/usr/share/man/man1/ls.1.gz
			
指定手册位置
man -M /home/mysql/man mysql
			

1.2. getconf - Query system configuration variables

	
$ getconf LONG_BIT
32
$ getconf WORD_BIT
32
	
	
	
LINK_MAX                           65000
_POSIX_LINK_MAX                    65000
MAX_CANON                          255
_POSIX_MAX_CANON                   255
MAX_INPUT                          255
_POSIX_MAX_INPUT                   255
NAME_MAX                           255
_POSIX_NAME_MAX                    255
PATH_MAX                           4096
_POSIX_PATH_MAX                    4096
PIPE_BUF                           4096
_POSIX_PIPE_BUF                    4096
SOCK_MAXBUF
_POSIX_ASYNC_IO
_POSIX_CHOWN_RESTRICTED            1
_POSIX_NO_TRUNC                    1
_POSIX_PRIO_IO
_POSIX_SYNC_IO
_POSIX_VDISABLE                    0
ARG_MAX                            2097152
ATEXIT_MAX                         2147483647
CHAR_BIT                           8
CHAR_MAX                           127
CHAR_MIN                           -128
CHILD_MAX                          63918
CLK_TCK                            100
INT_MAX                            2147483647
INT_MIN                            -2147483648
IOV_MAX                            1024
LOGNAME_MAX                        256
LONG_BIT                           64
MB_LEN_MAX                         16
NGROUPS_MAX                        65536
NL_ARGMAX                          4096
NL_LANGMAX                         2048
NL_MSGMAX                          2147483647
NL_NMAX                            2147483647
NL_SETMAX                          2147483647
NL_TEXTMAX                         2147483647
NSS_BUFLEN_GROUP                   1024
NSS_BUFLEN_PASSWD                  1024
NZERO                              20
OPEN_MAX                           1024
PAGESIZE                           4096
PAGE_SIZE                          4096
PASS_MAX                           8192
PTHREAD_DESTRUCTOR_ITERATIONS      4
PTHREAD_KEYS_MAX                   1024
PTHREAD_STACK_MIN                  16384
PTHREAD_THREADS_MAX
SCHAR_MAX                          127
SCHAR_MIN                          -128
SHRT_MAX                           32767
SHRT_MIN                           -32768
SSIZE_MAX                          32767
TTY_NAME_MAX                       32
TZNAME_MAX
UCHAR_MAX                          255
UINT_MAX                           4294967295
UIO_MAXIOV                         1024
ULONG_MAX                          18446744073709551615
USHRT_MAX                          65535
WORD_BIT                           32
_AVPHYS_PAGES                      972844
_NPROCESSORS_CONF                  8
_NPROCESSORS_ONLN                  8
_PHYS_PAGES                        4106156
_POSIX_ARG_MAX                     2097152
_POSIX_ASYNCHRONOUS_IO             200809
_POSIX_CHILD_MAX                   63918
_POSIX_FSYNC                       200809
_POSIX_JOB_CONTROL                 1
_POSIX_MAPPED_FILES                200809
_POSIX_MEMLOCK                     200809
_POSIX_MEMLOCK_RANGE               200809
_POSIX_MEMORY_PROTECTION           200809
_POSIX_MESSAGE_PASSING             200809
_POSIX_NGROUPS_MAX                 65536
_POSIX_OPEN_MAX                    1024
_POSIX_PII
_POSIX_PII_INTERNET
_POSIX_PII_INTERNET_DGRAM
_POSIX_PII_INTERNET_STREAM
_POSIX_PII_OSI
_POSIX_PII_OSI_CLTS
_POSIX_PII_OSI_COTS
_POSIX_PII_OSI_M
_POSIX_PII_SOCKET
_POSIX_PII_XTI
_POSIX_POLL
_POSIX_PRIORITIZED_IO              200809
_POSIX_PRIORITY_SCHEDULING         200809
_POSIX_REALTIME_SIGNALS            200809
_POSIX_SAVED_IDS                   1
_POSIX_SELECT
_POSIX_SEMAPHORES                  200809
_POSIX_SHARED_MEMORY_OBJECTS       200809
_POSIX_SSIZE_MAX                   32767
_POSIX_STREAM_MAX                  16
_POSIX_SYNCHRONIZED_IO             200809
_POSIX_THREADS                     200809
_POSIX_THREAD_ATTR_STACKADDR       200809
_POSIX_THREAD_ATTR_STACKSIZE       200809
_POSIX_THREAD_PRIORITY_SCHEDULING  200809
_POSIX_THREAD_PRIO_INHERIT         200809
_POSIX_THREAD_PRIO_PROTECT         200809
_POSIX_THREAD_ROBUST_PRIO_INHERIT
_POSIX_THREAD_ROBUST_PRIO_PROTECT
_POSIX_THREAD_PROCESS_SHARED       200809
_POSIX_THREAD_SAFE_FUNCTIONS       200809
_POSIX_TIMERS                      200809
TIMER_MAX
_POSIX_TZNAME_MAX
_POSIX_VERSION                     200809
_T_IOV_MAX
_XOPEN_CRYPT
_XOPEN_ENH_I18N                    1
_XOPEN_LEGACY                      1
_XOPEN_REALTIME                    1
_XOPEN_REALTIME_THREADS            1
_XOPEN_SHM                         1
_XOPEN_UNIX                        1
_XOPEN_VERSION                     700
_XOPEN_XCU_VERSION                 4
_XOPEN_XPG2                        1
_XOPEN_XPG3                        1
_XOPEN_XPG4                        1
BC_BASE_MAX                        99
BC_DIM_MAX                         2048
BC_SCALE_MAX                       99
BC_STRING_MAX                      1000
CHARCLASS_NAME_MAX                 2048
COLL_WEIGHTS_MAX                   255
EQUIV_CLASS_MAX
EXPR_NEST_MAX                      32
LINE_MAX                           2048
POSIX2_BC_BASE_MAX                 99
POSIX2_BC_DIM_MAX                  2048
POSIX2_BC_SCALE_MAX                99
POSIX2_BC_STRING_MAX               1000
POSIX2_CHAR_TERM                   200809
POSIX2_COLL_WEIGHTS_MAX            255
POSIX2_C_BIND                      200809
POSIX2_C_DEV                       200809
POSIX2_C_VERSION                   200809
POSIX2_EXPR_NEST_MAX               32
POSIX2_FORT_DEV
POSIX2_FORT_RUN
_POSIX2_LINE_MAX                   2048
POSIX2_LINE_MAX                    2048
POSIX2_LOCALEDEF                   200809
POSIX2_RE_DUP_MAX                  32767
POSIX2_SW_DEV                      200809
POSIX2_UPE
POSIX2_VERSION                     200809
RE_DUP_MAX                         32767
PATH                               /bin:/usr/bin
CS_PATH                            /bin:/usr/bin
LFS_CFLAGS
LFS_LDFLAGS
LFS_LIBS
LFS_LINTFLAGS
LFS64_CFLAGS                       -D_LARGEFILE64_SOURCE
LFS64_LDFLAGS
LFS64_LIBS
LFS64_LINTFLAGS                    -D_LARGEFILE64_SOURCE
_XBS5_WIDTH_RESTRICTED_ENVS        XBS5_LP64_OFF64
XBS5_WIDTH_RESTRICTED_ENVS         XBS5_LP64_OFF64
_XBS5_ILP32_OFF32
XBS5_ILP32_OFF32_CFLAGS
XBS5_ILP32_OFF32_LDFLAGS
XBS5_ILP32_OFF32_LIBS
XBS5_ILP32_OFF32_LINTFLAGS
_XBS5_ILP32_OFFBIG
XBS5_ILP32_OFFBIG_CFLAGS
XBS5_ILP32_OFFBIG_LDFLAGS
XBS5_ILP32_OFFBIG_LIBS
XBS5_ILP32_OFFBIG_LINTFLAGS
_XBS5_LP64_OFF64                   1
XBS5_LP64_OFF64_CFLAGS             -m64
XBS5_LP64_OFF64_LDFLAGS            -m64
XBS5_LP64_OFF64_LIBS
XBS5_LP64_OFF64_LINTFLAGS
_XBS5_LPBIG_OFFBIG
XBS5_LPBIG_OFFBIG_CFLAGS
XBS5_LPBIG_OFFBIG_LDFLAGS
XBS5_LPBIG_OFFBIG_LIBS
XBS5_LPBIG_OFFBIG_LINTFLAGS
_POSIX_V6_ILP32_OFF32
POSIX_V6_ILP32_OFF32_CFLAGS
POSIX_V6_ILP32_OFF32_LDFLAGS
POSIX_V6_ILP32_OFF32_LIBS
POSIX_V6_ILP32_OFF32_LINTFLAGS
_POSIX_V6_WIDTH_RESTRICTED_ENVS    POSIX_V6_LP64_OFF64
POSIX_V6_WIDTH_RESTRICTED_ENVS     POSIX_V6_LP64_OFF64
_POSIX_V6_ILP32_OFFBIG
POSIX_V6_ILP32_OFFBIG_CFLAGS
POSIX_V6_ILP32_OFFBIG_LDFLAGS
POSIX_V6_ILP32_OFFBIG_LIBS
POSIX_V6_ILP32_OFFBIG_LINTFLAGS
_POSIX_V6_LP64_OFF64               1
POSIX_V6_LP64_OFF64_CFLAGS         -m64
POSIX_V6_LP64_OFF64_LDFLAGS        -m64
POSIX_V6_LP64_OFF64_LIBS
POSIX_V6_LP64_OFF64_LINTFLAGS
_POSIX_V6_LPBIG_OFFBIG
POSIX_V6_LPBIG_OFFBIG_CFLAGS
POSIX_V6_LPBIG_OFFBIG_LDFLAGS
POSIX_V6_LPBIG_OFFBIG_LIBS
POSIX_V6_LPBIG_OFFBIG_LINTFLAGS
_POSIX_V7_ILP32_OFF32
POSIX_V7_ILP32_OFF32_CFLAGS
POSIX_V7_ILP32_OFF32_LDFLAGS
POSIX_V7_ILP32_OFF32_LIBS
POSIX_V7_ILP32_OFF32_LINTFLAGS
_POSIX_V7_WIDTH_RESTRICTED_ENVS    POSIX_V7_LP64_OFF64
POSIX_V7_WIDTH_RESTRICTED_ENVS     POSIX_V7_LP64_OFF64
_POSIX_V7_ILP32_OFFBIG
POSIX_V7_ILP32_OFFBIG_CFLAGS
POSIX_V7_ILP32_OFFBIG_LDFLAGS
POSIX_V7_ILP32_OFFBIG_LIBS
POSIX_V7_ILP32_OFFBIG_LINTFLAGS
_POSIX_V7_LP64_OFF64               1
POSIX_V7_LP64_OFF64_CFLAGS         -m64
POSIX_V7_LP64_OFF64_LDFLAGS        -m64
POSIX_V7_LP64_OFF64_LIBS
POSIX_V7_LP64_OFF64_LINTFLAGS
_POSIX_V7_LPBIG_OFFBIG
POSIX_V7_LPBIG_OFFBIG_CFLAGS
POSIX_V7_LPBIG_OFFBIG_LDFLAGS
POSIX_V7_LPBIG_OFFBIG_LIBS
POSIX_V7_LPBIG_OFFBIG_LINTFLAGS
_POSIX_ADVISORY_INFO               200809
_POSIX_BARRIERS                    200809
_POSIX_BASE
_POSIX_C_LANG_SUPPORT
_POSIX_C_LANG_SUPPORT_R
_POSIX_CLOCK_SELECTION             200809
_POSIX_CPUTIME                     200809
_POSIX_THREAD_CPUTIME              200809
_POSIX_DEVICE_SPECIFIC
_POSIX_DEVICE_SPECIFIC_R
_POSIX_FD_MGMT
_POSIX_FIFO
_POSIX_PIPE
_POSIX_FILE_ATTRIBUTES
_POSIX_FILE_LOCKING
_POSIX_FILE_SYSTEM
_POSIX_MONOTONIC_CLOCK             200809
_POSIX_MULTI_PROCESS
_POSIX_SINGLE_PROCESS
_POSIX_NETWORKING
_POSIX_READER_WRITER_LOCKS         200809
_POSIX_SPIN_LOCKS                  200809
_POSIX_REGEXP                      1
_REGEX_VERSION
_POSIX_SHELL                       1
_POSIX_SIGNALS
_POSIX_SPAWN                       200809
_POSIX_SPORADIC_SERVER
_POSIX_THREAD_SPORADIC_SERVER
_POSIX_SYSTEM_DATABASE
_POSIX_SYSTEM_DATABASE_R
_POSIX_TIMEOUTS                    200809
_POSIX_TYPED_MEMORY_OBJECTS
_POSIX_USER_GROUPS
_POSIX_USER_GROUPS_R
POSIX2_PBS
POSIX2_PBS_ACCOUNTING
POSIX2_PBS_LOCATE
POSIX2_PBS_TRACK
POSIX2_PBS_MESSAGE
SYMLOOP_MAX
STREAM_MAX                         16
AIO_LISTIO_MAX
AIO_MAX
AIO_PRIO_DELTA_MAX                 20
DELAYTIMER_MAX                     2147483647
HOST_NAME_MAX                      64
LOGIN_NAME_MAX                     256
MQ_OPEN_MAX
MQ_PRIO_MAX                        32768
_POSIX_DEVICE_IO
_POSIX_TRACE
_POSIX_TRACE_EVENT_FILTER
_POSIX_TRACE_INHERIT
_POSIX_TRACE_LOG
RTSIG_MAX                          32
SEM_NSEMS_MAX
SEM_VALUE_MAX                      2147483647
SIGQUEUE_MAX                       63918
FILESIZEBITS                       64
POSIX_ALLOC_SIZE_MIN               4096
POSIX_REC_INCR_XFER_SIZE
POSIX_REC_MAX_XFER_SIZE
POSIX_REC_MIN_XFER_SIZE            4096
POSIX_REC_XFER_ALIGN               4096
SYMLINK_MAX
GNU_LIBC_VERSION                   glibc 2.28
GNU_LIBPTHREAD_VERSION             NPTL 2.28
POSIX2_SYMLINKS                    1
LEVEL1_ICACHE_SIZE                 65536
LEVEL1_ICACHE_ASSOC                2
LEVEL1_ICACHE_LINESIZE             64
LEVEL1_DCACHE_SIZE                 65536
LEVEL1_DCACHE_ASSOC                2
LEVEL1_DCACHE_LINESIZE             64
LEVEL2_CACHE_SIZE                  524288
LEVEL2_CACHE_ASSOC                 16
LEVEL2_CACHE_LINESIZE              64
LEVEL3_CACHE_SIZE                  16777216
LEVEL3_CACHE_ASSOC                 16
LEVEL3_CACHE_LINESIZE              64
LEVEL4_CACHE_SIZE                  0
LEVEL4_CACHE_ASSOC                 0
LEVEL4_CACHE_LINESIZE              0
IPV6                               200809
RAW_SOCKETS                        200809
_POSIX_IPV6                        200809
_POSIX_RAW_SOCKETS                 200809
	
	

1.3. 快捷键

		
Ctrl+p shell中上一个命令,或者 文本中移动到上一行
Ctrl+n shell中下一个命令,或者 文本中移动到下一行
Ctrl+r 往后搜索历史命令
Ctrl+s 往前搜索历史命令
Ctrl+f 光标前移
Ctrl+b 光标后退
Ctrl+a 到行首
Ctrl+e 到行尾
Ctrl+d 删除一个字符,删除一个字符,相当于通常的Delete键
Ctrl+h 退格删除一个字符,相当于通常的Backspace键
Ctrl+u 删除到行首
Ctrl+k 删除到行尾
Ctrl+l 类似 clear 命令效果
Ctrl+y 粘贴
		
		

1.3.1. 命令行编辑命令

		
Ctrl + a :移到命令行首
Ctrl + e :移到命令行尾
Ctrl + f :按字符前移(右向)
Ctrl + b :按字符后移(左向)
Alt + f :按单词前移(右向)
Alt + b :按单词后移(左向)
Ctrl + xx:在命令行首和光标之间移动
Ctrl + u :从光标处删除至命令行首
Ctrl + k :从光标处删除至命令行尾
Ctrl + w :从光标处删除至字首
Alt + d :从光标处删除至字尾
Ctrl + d :删除光标处的字符
Ctrl + h :删除光标前的字符
Ctrl + y :粘贴至光标后
Alt + c :从光标处更改为首字母大写的单词
Alt + u :从光标处更改为全部大写的单词
Alt + l :从光标处更改为全部小写的单词
Ctrl + t :交换光标处和之前的字符
Alt + t :交换光标处和之前的单词
Alt + Backspace:与 Ctrl + w 相同类似,分隔符有些差别
		
			

1.3.2. 重新执行命令快捷键

			
Ctrl + r:逆向搜索命令历史
Ctrl + g:从历史搜索模式退出
Ctrl + p:历史中的上一条命令
Ctrl + n:历史中的下一条命令
Alt + .:使用上一条命令的最后一个参数
			
			

1.3.3. 终端控制快捷键

			
Ctrl + l:清屏
Ctrl + o:执行当前命令,并选择上一条命令
Ctrl + s:阻止屏幕输出
Ctrl + q:允许屏幕输出
Ctrl + c:终止命令
Ctrl + z:挂起命令
			
			

1.3.4. Bang (!) 命令

			
!!:执行上一条命令
!blah:执行最近的以 blah 开头的命令,如 !ls
!blah:p:仅打印输出,而不执行
!$:上一条命令的最后一个参数,与 Alt + . 相同
!$:p:打印输出 !$ 的内容
!*:上一条命令的所有参数
!*:p:打印输出 !* 的内容
^neo:删除上一条命令中的 neo
^neo^foo:将上一条命令中的 neo 替换为 foo
^neo^foo^:将上一条命令中所有的 neo 都替换为 foo
			
			

^ 是 bash/zsh 用法,在 fish 中不能使用

			
[root@netkiller ~]# ls /bin
[root@netkiller ~]# ^ls^ll
ll /bin
lrwxrwxrwx. 1 root root 7 2022-05-16 20:28 /bin -> usr/bin
[root@netkiller ~]#
			
			

1.4. chsh - change login shell

# chsh --list
/bin/sh
/bin/bash
/sbin/nologin
/bin/tcsh
/bin/csh
/bin/ksh

# chsh --list-shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/zsh
		
$ chsh -s /bin/zsh
or
$ usermod -s /bin/zsh
		

show me current shell

neo@netkiller:~$ echo $SHELL
/bin/zsh

neo@netkiller:~$ cat /etc/passwd|grep neo
neo:x:1000:1000:Neo Chen,,,:/home/neo:/bin/zsh
		

1.5. 执行程序返回值

		
"OS error code 1: Operation not permitted"
"OS error code 2: No such file or directory"
"OS error code 3: No such process"
"OS error code 4: Interrupted system call"
"OS error code 5: Input/output error"
"OS error code 6: No such device or address"
"OS error code 7: Argument list too long"
"OS error code 8: Exec format error"
"OS error code 9: Bad file descriptor"
"OS error code 10: No child processes"
"OS error code 11: Resource temporarily unavailable"
"OS error code 12: Cannot allocate memory"
"OS error code 13: Permission denied"
"OS error code 14: Bad address"
"OS error code 15: Block device required"
"OS error code 16: Device or resource busy"
"OS error code 17: File exists"
"OS error code 18: Invalid cross-device link"
"OS error code 19: No such device"
"OS error code 20: Not a directory"
"OS error code 21: Is a directory"
"OS error code 22: Invalid argument"
"OS error code 23: Too many open files in system"
"OS error code 24: Too many open files"
"OS error code 25: Inappropriate ioctl for device"
"OS error code 26: Text file busy"
"OS error code 27: File too large"
"OS error code 28: No space left on device"
"OS error code 29: Illegal seek"
"OS error code 30: Read-only file system"
"OS error code 31: Too many links"
"OS error code 32: Broken pipe"
"OS error code 33: Numerical argument out of domain"
"OS error code 34: Numerical result out of range"
"OS error code 35: Resource deadlock avoided"
"OS error code 36: File name too long"
"OS error code 37: No locks available"
"OS error code 38: Function not implemented"
"OS error code 39: Directory not empty"
"OS error code 40: Too many levels of symbolic links"
"OS error code 42: No message of desired type"
"OS error code 43: Identifier removed"
"OS error code 44: Channel number out of range"
"OS error code 45: Level 2 not synchronized"
"OS error code 46: Level 3 halted"
"OS error code 47: Level 3 reset"
"OS error code 48: Link number out of range"
"OS error code 49: Protocol driver not attached"
"OS error code 50: No CSI structure available"
"OS error code 51: Level 2 halted"
"OS error code 52: Invalid exchange"
"OS error code 53: Invalid request descriptor"
"OS error code 54: Exchange full"
"OS error code 55: No anode"
"OS error code 56: Invalid request code"
"OS error code 57: Invalid slot"
"OS error code 59: Bad font file format"
"OS error code 60: Device not a stream"
"OS error code 61: No data available"
"OS error code 62: Timer expired"
"OS error code 63: Out of streams resources"
"OS error code 64: Machine is not on the network"
"OS error code 65: Package not installed"
"OS error code 66: Object is remote"
"OS error code 67: Link has been severed"
"OS error code 68: Advertise error"
"OS error code 69: Srmount error"
"OS error code 70: Communication error on send"
"OS error code 71: Protocol error"
"OS error code 72: Multihop attempted"
"OS error code 73: RFS specific error"
"OS error code 74: Bad message"
"OS error code 75: Value too large for defined data type"
"OS error code 76: Name not unique on network"
"OS error code 77: File descriptor in bad state"
"OS error code 78: Remote address changed"
"OS error code 79: Can not access a needed shared library"
"OS error code 80: Accessing a corrupted shared library"
"OS error code 81: .lib section in a.out corrupted"
"OS error code 82: Attempting to link in too many shared libraries"
"OS error code 83: Cannot exec a shared library directly"
"OS error code 84: Invalid or incomplete multibyte or wide character"
"OS error code 85: Interrupted system call should be restarted"
"OS error code 86: Streams pipe error"
"OS error code 87: Too many users"
"OS error code 88: Socket operation on non-socket"
"OS error code 89: Destination address required"
"OS error code 90: Message too long"
"OS error code 91: Protocol wrong type for socket"
"OS error code 92: Protocol not available"
"OS error code 93: Protocol not supported"
"OS error code 94: Socket type not supported"
"OS error code 95: Operation not supported"
"OS error code 96: Protocol family not supported"
"OS error code 97: Address family not supported by protocol"
"OS error code 98: Address already in use"
"OS error code 99: Cannot assign requested address"
"OS error code 100: Network is down"
"OS error code 101: Network is unreachable"
"OS error code 102: Network dropped connection on reset"
"OS error code 103: Software caused connection abort"
"OS error code 104: Connection reset by peer"
"OS error code 105: No buffer space available"
"OS error code 106: Transport endpoint is already connected"
"OS error code 107: Transport endpoint is not connected"
"OS error code 108: Cannot send after transport endpoint shutdown"
"OS error code 109: Too many references: cannot splice"
"OS error code 110: Connection timed out"
"OS error code 111: Connection refused"
"OS error code 112: Host is down"
"OS error code 113: No route to host"
"OS error code 114: Operation already in progress"
"OS error code 115: Operation now in progress"
"OS error code 116: Stale NFS file handle"
"OS error code 117: Structure needs cleaning"
"OS error code 118: Not a XENIX named type file"
"OS error code 119: No XENIX semaphores available"
"OS error code 120: Is a named type file"
"OS error code 121: Remote I/O error"
"OS error code 122: Disk quota exceeded"
"OS error code 123: No medium found"
"OS error code 124: Wrong medium type"
"OS error code 125: Operation canceled"
"OS error code 126: Required key not available"
"OS error code 127: Key has expired"
"OS error code 128: Key has been revoked"
"OS error code 129: Key was rejected by service"
"OS error code 130: Owner died"
"OS error code 131: State not recoverable"
		
		

1.6. Z Shell

http://www.zsh.org/

1.6.1. installing Z shell

		
$ sudo apt install zsh
			
			

1.6.2. Oh My ZSH!

http://ohmyz.sh/

Oh My ZSH 是z shell命令主题

			
$ sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
			
			

1.6.3. Starting file

~/.zshrc
				
neo@netkiller:~$ cat .zshrc
# Created by newuser for 4.3.9
PROMPT='%n@%M:%~$ '

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    eval "`dircolors -b`"
    alias ls='ls --color=auto'
    alias dir='dir --color=auto'
    alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# some more ls aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'

# Home/End/Del key
bindkey '\e[1~' beginning-of-line
bindkey '\e[4~' end-of-line
bindkey "\e[3~" delete-char
				
				

1.6.4. Prompting

			
$ PROMPT='%n@%M:%~$ '
neo@netkiller:~$
			
			
			
autoload colors; colors
export PS1="%B[%{$fg[red]%}%n%{$reset_color%}%b@%B%{$fg[cyan]%}%m%b%{$reset_color%}:%~%B]%b "
			
			
			
[neo@netkiller:~/.oh-my-zsh/themes]
			
			

1.6.5. Aliases

			
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    eval "`dircolors -b`"
    alias ls='ls --color=auto'
    alias dir='dir --color=auto'
    alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# some more ls aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
			
			

1.6.6. History

			
$ !$
			
			
			
$ history
   18  cd workspace/Document
   19  ls
   20  ls

$ !20
ls
Docbook  makedoc  Tex
			
			

1.6.7. FAQ

Home/End key
				
bindkey '\e[1~' beginning-of-line
bindkey '\e[4~' end-of-line
				
				

1.7. Berkeley UNIX C shell (csh)

$ sudo apt install csh

1.8. KornShell

$ sudo apt install ksh

1.9. fish shell

1.9.1. 安装 fish shell

Linux 安装

         
dnf install -y fish        
        
        

1.9.2. 配置 fish

主题管理
             
fish_config theme show        
            
            

1.9.3. 环境变量

    	
set JAVA_HOME $(/usr/libexec/java_home)    	
    	
    	

1.10. 有趣的 Shell 应用

1.10.1. Ascii 星球大战电影

         
neo@MacBook-Pro-M2 ~>  nc towel.blinkenlights.nl 23        
        
		

1.10.2. 天气预报

         
neo@MacBook-Pro-M2 ~> curl http://wttr.in/
Weather report: Shenzhen, China

        \  /       Partly cloudy
    _ /"".-.     18 °C          
        \_(   ).   ↘ 26 km/h      
        /(___(__)  10 km          
                0.0 mm         
                                                        ┌─────────────┐                                                       
┌──────────────────────────────┬───────────────────────┤  Mon 09 Jan ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│               Overcast       │               Overcast       │               Overcast       │               Overcast       │
│      .--.     17 °C          │      .--.     21 °C          │      .--.     19 °C          │      .--.     18 °C          │
│   .-(    ).   ↓ 7-9 km/h     │   .-(    ).   ↙ 7-8 km/h     │   .-(    ).   ↙ 7-10 km/h    │   .-(    ).   ↙ 7-10 km/h    │
│  (___.__)__)  10 km          │  (___.__)__)  10 km          │  (___.__)__)  10 km          │  (___.__)__)  10 km          │
│               0.0 mm | 0%    │               0.0 mm | 0%    │               0.0 mm | 0%    │               0.0 mm | 0%    │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
                                                        ┌─────────────┐                                                       
┌──────────────────────────────┬───────────────────────┤  Tue 10 Jan ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Patchy rain po…│  _`/"".-.     Patchy rain po…│      .-.      Light drizzle  │               Overcast       │
│   ,\_(   ).   17 °C          │   ,\_(   ).   18 °C          │     (   ).    17 °C          │      .--.     16 °C          │
│    /(___(__)  ↙ 6-9 km/h     │    /(___(__)  ↙ 8-9 km/h     │    (___(__)   ↙ 9-13 km/h    │   .-(    ).   ↙ 7-10 km/h    │
│      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │     ‘ ‘ ‘ ‘   2 km           │  (___.__)__)  10 km          │
│     ‘ ‘ ‘ ‘   0.1 mm | 61%   │     ‘ ‘ ‘ ‘   0.1 mm | 81%   │    ‘ ‘ ‘ ‘    0.7 mm | 83%   │               0.0 mm | 0%    │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
                                                        ┌─────────────┐                                                       
┌──────────────────────────────┬───────────────────────┤  Wed 11 Jan ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Patchy rain po…│  _`/"".-.     Patchy rain po…│    \  /       Partly cloudy  │    \  /       Partly cloudy  │
│   ,\_(   ).   16 °C          │   ,\_(   ).   17 °C          │  _ /"".-.     18 °C          │  _ /"".-.     17 °C          │
│    /(___(__)  ↙ 5-7 km/h     │    /(___(__)  ↙ 5-6 km/h     │    \_(   ).   ↙ 7-9 km/h     │    \_(   ).   ← 7-11 km/h    │
│      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │    /(___(__)  10 km          │    /(___(__)  10 km          │
│     ‘ ‘ ‘ ‘   0.1 mm | 87%   │     ‘ ‘ ‘ ‘   0.1 mm | 84%   │               0.0 mm | 0%    │               0.0 mm | 0%    │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘

Follow @igor_chubin for wttr.in updates    
        
		

1.10.3. htop - interactive process viewer

		

1.10.4. elinks

1.10.5. chat

finch,irssi

1.11. test - 条件判断命令

test 命令用于条件判断,返回 0(真)或非 0(假)。在 shell 脚本中常用于 if、while 等控制结构。方括号 [ ] 是 test 命令的另一种写法。

判断目录

				
	test -d /path/to/directory || mkdir -p /path/to/directory
				
			

检查环境变量

			
		test -x $HAPROXY || exit 0
		test -f "$CONFIG" || exit 0
			
			

基本语法

test EXPRESSION
[ EXPRESSION ]

# 两种写法等价:
test -f /etc/passwd
[ -f /etc/passwd ]
			

注意:[EXPRESSION 以及 ] 之间必须有空格。

文件测试操作符

测试文件属性的常用操作符:

  • -e file - 文件存在

  • -f file - 文件存在且是普通文件

  • -d file - 文件存在且是目录

  • -r file - 文件存在且可读

  • -w file - 文件存在且可写

  • -x file - 文件存在且可执行

  • -s file - 文件存在且大小大于 0

  • -L file - 文件存在且是符号链接

  • -O file - 文件存在且属于当前用户

  • -G file - 文件存在且属于当前组

  • -N file - 文件存在且上次读取后被修改过

  • -c file - 文件存在且是字符特殊文件

  • -b file - 文件存在且是块特殊文件

  • -S file - 文件存在且是套接字

  • -p file - 文件存在且是命名管道

文件比较:

  • file1 -nt file2 - file1 比 file2 新(mtime)

  • file1 -ot file2 - file1 比 file2 旧

  • file1 -ef file2 - file1 和 file2 有相同的 device 和 inode

示例:

# 检查文件是否存在
test -f /etc/passwd && echo "文件存在"

# 检查目录是否存在
[ -d /var/log ] && echo "目录存在"

# 检查文件是否可执行
[ -x /usr/bin/munin-cron ] && /usr/bin/munin-cron

# 检查文件是否为空
if [ ! -s /tmp/log.txt ]; then
    echo "文件为空或不存在"
fi

# 比较两个文件的新旧
if [ file1.txt -nt file2.txt ]; then
    echo "file1.txt 比 file2.txt 新"
fi
			

字符串测试操作符

字符串比较操作符:

  • -z string - 字符串长度为 0(空字符串)

  • -n string - 字符串长度不为 0(非空字符串)

  • string1 = string2 - 字符串相等

  • string1 != string2 - 字符串不等

示例:

# 检查变量是否为空
name=""
if [ -z "$name" ]; then
    echo "变量为空"
fi

# 检查变量是否非空
name="neo"
[ -n "$name" ] && echo "变量非空: $name"

# 字符串相等比较
user="root"
if [ "$user" = "root" ]; then
    echo "是 root 用户"
fi

# 字符串不等比较
if [ "$user" != "guest" ]; then
    echo "不是 guest 用户"
fi

# 注意:变量应该用引号包裹,防止 word splitting
[ "$var" = "value" ]  # 正确
[ $var = "value" ]    # 危险:如果 $var 为空会报错
			

整数比较操作符

整数比较操作符:

  • n1 -eq n2 - n1 等于 n2

  • n1 -ne n2 - n1 不等于 n2

  • n1 -lt n2 - n1 小于 n2

  • n1 -le n2 - n1 小于等于 n2

  • n1 -gt n2 - n1 大于 n2

  • n1 -ge n2 - n1 大于等于 n2

示例:

# 检查数字是否相等
count=5
if [ "$count" -eq 5 ]; then
    echo "计数为 5"
fi

# 检查数字范围
age=25
if [ "$age" -ge 18 ] && [ "$age" -le 65 ]; then
    echo "年龄在 18-65 之间"
fi

# 检查进程数
procs=$(ps aux | wc -l)
if [ "$procs" -gt 100 ]; then
    echo "进程数过多: $procs"
fi

# 检查返回值
command
if [ $? -ne 0 ]; then
    echo "命令执行失败"
fi
			

记忆技巧:

  • eq = equal

  • ne = not equal

  • lt = less than

  • le = less than or equal

  • gt = greater than

  • ge = greater than or equal

逻辑操作符

组合多个条件:

  • expr1 -a expr2 - 逻辑与(expr1 和 expr2 都为真)

  • expr1 -o expr2 - 逻辑或(expr1 或 expr2 为真)

  • ! expr - 逻辑非

使用 shell 操作符(推荐):

  • expr1 && expr2 - 逻辑与

  • expr1 || expr2 - 逻辑或

  • ! expr - 逻辑非

示例:

# 逻辑与:文件存在且可执行
[ -f /usr/bin/munin-cron ] && [ -x /usr/bin/munin-cron ] && /usr/bin/munin-cron

# 使用 test 的 -a 操作符
test -f /etc/passwd -a -r /etc/passwd && echo "文件存在且可读"

# 逻辑或:目录不存在则创建
[ -d /tmp/test ] || mkdir /tmp/test

# 逻辑非:文件不存在
[ ! -f /tmp/lock ] && echo "锁文件不存在"

# 复杂条件组合
if [ -f "$file" ] && [ -r "$file" ] && [ -s "$file" ]; then
    echo "文件存在、可读且非空"
fi

# 嵌套条件
if [ "$user" = "root" ] || ([ "$user" = "admin" ] && [ -w "$file" ]); then
    echo "有权限"
fi
			

在 if 语句中使用

# 基本 if 结构
if [ -f /etc/passwd ]; then
    echo "文件存在"
fi

# if-else 结构
if [ -d /var/log ]; then
    echo "目录存在"
else
    echo "目录不存在"
fi

# if-elif-else 结构
if [ -f "$file" ]; then
    echo "是普通文件"
elif [ -d "$file" ]; then
    echo "是目录"
elif [ -L "$file" ]; then
    echo "是符号链接"
else
    echo "未知类型"
fi

# 多条件判断
if [ -f "$config" ] && [ -r "$config" ]; then
    source "$config"
elif [ -f "$default_config" ]; then
    source "$default_config"
else
    echo "没有配置文件"
    exit 1
fi
			

在 while/until 循环中使用

# while 循环:条件为真时执行
count=0
while [ $count -lt 5 ]; do
    echo "计数: $count"
    count=$((count + 1))
done

# until 循环:条件为假时执行
until [ -f /tmp/ready ]; do
    echo "等待文件创建..."
    sleep 2
done

# 读取用户输入
while [ "$answer" != "yes" ] && [ "$answer" != "no" ]; do
    read -p "请输入 yes 或 no: " answer
done
			

实际应用示例

# 检查命令是否存在
if [ -x /usr/bin/git ]; then
    echo "git 已安装"
else
    echo "git 未安装"
    exit 1
fi

# 检查用户权限
if [ "$(id -u)" -ne 0 ]; then
    echo "需要 root 权限运行"
    exit 1
fi

# 文件备份脚本
src="/data/important.db"
backup="/backup/$(date +%Y%m%d)_important.db"
if [ -f "$src" ] && [ -s "$src" ]; then
    cp "$src" "$backup"
    echo "备份成功: $backup"
else
    echo "源文件不存在或为空"
    exit 1
fi

# 检查磁盘空间
available=$(df / | tail -1 | awk '{print $4}')
threshold=1048576  # 1GB in KB
if [ "$available" -lt "$threshold" ]; then
    echo "警告:磁盘空间不足 1GB"
fi

# 等待服务启动
timeout=30
count=0
while [ $count -lt $timeout ]; do
    if [ -S /var/run/mysql.sock ]; then
        echo "MySQL 已启动"
        break
    fi
    sleep 1
    count=$((count + 1))
done

if [ $count -eq $timeout ]; then
    echo "MySQL 启动超时"
    exit 1
fi
			

[[ ]] 扩展测试(Bash 特有)

Bash 提供 [[ ]] 作为 [ ] 的增强版本:

  • 支持正则表达式匹配:=~

  • 支持 &&|| 在测试内部使用

  • 不需要对变量加引号(自动处理)

  • 支持模式匹配:== 配合通配符

# 正则表达式匹配
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
    echo "有效的邮箱地址"
fi

# 模式匹配
if [[ "$filename" == *.jpg ]]; then
    echo "是 JPEG 图片"
fi

# 内部使用逻辑操作符
if [[ -f "$file" && -r "$file" ]]; then
    echo "文件存在且可读"
fi

# 字符串比较(不需要引号)
if [[ $user == root ]]; then
    echo "是 root 用户"
fi

# 字典序比较
if [[ "apple" < "banana" ]]; then
    echo "apple 在 banana 之前"
fi
			

注意:[[ ]] 是 Bash 扩展,不兼容 POSIX sh。如果需要可移植性,使用 [ ]

常见陷阱

# 错误:方括号内没有空格
if [-f /etc/passwd]; then  # 错误!
if [ -f /etc/passwd ]; then  # 正确

# 错误:整数比较使用字符串操作符
if [ "$count" = "5" ]; then  # 字符串比较
if [ "$count" -eq 5 ]; then  # 整数比较(正确)

# 危险:未加引号的变量
if [ $file = "test.txt" ]; then  # 如果 $file 为空会报错
if [ "$file" = "test.txt" ]; then  # 安全

# 错误:使用 = 比较数字
if [ $age = 18 ]; then  # 字符串比较
if [ $age -eq 18 ]; then  # 整数比较(正确)

# 错误:在 [ ] 中使用 && 和 ||
if [ -f file1 && -f file2 ]; then  # 错误!
if [ -f file1 ] && [ -f file2 ]; then  # 正确
			

返回值检查

test 命令的返回值($?):

# 0 表示真,非 0 表示假
test -f /etc/passwd
echo $?  # 输出: 0(文件存在)

test -f /nonexistent
echo $?  # 输出: 1(文件不存在)

# 在脚本中检查返回值
command
if [ $? -eq 0 ]; then
    echo "命令成功"
else
    echo "命令失败,退出码: $?"
fi

# 简写形式
command && echo "成功" || echo "失败"