shell命令 按关键字 - zhongjiajie/zhongjiajie.github.com GitHub Wiki

shell命令-按关键字

资料

shell命令与全称对应表

shell命令 对应的全称
ls list
cd change directory
cat concatenate
touch
mv move file
cp copy file
su switch user
rm remove
df disk free
du disk usage
xargs extended arguments
mkdir make directory
rmdir remove directory
man manual
umount unmount
ps process status
ln link
ssh secure shell
pwd print work directory
vim vi improved
ping packet internet grouper
printf print formatted
wc word count
awk "aho weiberger and kernighan" 三个作者的姓的第一个字母
sed stream editor
uniq unique
telnet teminal over network
exec execute
passwd password
tar tape archive
cal calendar
cmp compare
daemon disk and execution monitor
egrep extended grep
fgrep fixed grep
chown change owner
chmod change mode
chgrp change group
chsh change shell
fsck file system check
mkfs make file system
fmt format
fg foreground
bg background
tty teletypewriter
pty pseudo tty
stty set tty
ssl secure sockets layer
terminfo terminal information
tz timezone
rpm redhat package manager
dpkg debian package manager
apt advanced package tool

cd

切换目录

  • cd /path: 切换到对应的目录
  • cd -: 切换到上一级目录,上一个目录会以环境变量$OLDPWD存储起来,cd -等同于cd $OLDPWD

curl

  • curl模拟get请求: curl -XGET 127.0.0.1/api或者不带任何参数curl https://www.example.com
  • curl模拟post请求
    • 发送键值对参数: curl -XPOST 127.0.0.1/api -d "param1=value1&param2=value2"
    • 发送json格式参数: curl -XPOST 127.0.0.1/api -H "Content-type: application/json" -d '{"param1":"value1","param2": "value2"}'
  • curl的部分参数:
    • -X: 指定HTTP请求
    • -i: 显示全部信息
    • -l: 只显示头部信息
    • -v: 显示get请求全过程解析
    • -d: 发送POST请求数据体curl -X POST -d'login=emma&password=123' https://google.com/login,使用-d参数curl会默认是post请求,所以可以省略POST关键字.且会在header中加入Content-Type : application/x-www-form-urlencoded
    • -A: User-Agent,-A 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'将User-Agent改成chrome浏览器
    • -H: 访问的headers,可以指定任意的header,例如-H 'User-Agent: php/1.0'
    • -F: 上传二进制文件,curl -F '[email protected]' https://google.com/profile,且可以指定类型curl -F '[email protected];type=image/png' https://google.com/profile,以及指定名称curl -F '[email protected];filename=me.png' https://google.com/profile
    • -G: 构造查询参数,curl -G -d 'q=kitties' -d 'count=20' https://google.com/search等同于https://google.com/search?q=kitties&count=20GET请求,如果删除-G会变成一个POST请求
    • -x: 使用代理,curl -x socks5://127.0.0.1:1086 https://www.example.com,使用代理访问网站,也是brew命令能翻墙的原理
    • -o: 将服务器回应保存成一个文件,相等于wget,curl -o example.html https://www.example.com,会生成一个example.html文件
    • -O: 将服务器回应保存成一个文件且URL最后部分作为文件名,curl -O https://www.example.com/foo/bar.html会生成一个bar.html文件名
    • -b: 发送cookie,curl -b 'foo=bar' -b 'foo2=baz' https://google.com,从文件中读取cookiecurl -b cookies.txt https://www.google.com
    • -c: 将返回的cookie写入文件curl -c cookies.txt https://www.google.com
    • -e: Referer请求的来源,curl -e 'https://google.com?q=example' https://www.example.com
    • -u: 设置服务器的用户名/密码,curl -u 'bob:12345' https://google.com/login

ls

列出当前目录下的文件及文件夹ls,列出指定目录的文件或文件夹ls /path/to/folder

常用选项:

  • -l: 以长格式显示列出文件或文件夹的详细信息
  • -S: 按照文件由小到大排序,默认是降序排列,如果想要升序用-rS
  • -h: 将文件或文件夹的大小转换成更加易读的格式,如 K M G
  • -t: sort by modification time,newest first

ln

NAME
     link, ln -- make links

SYNOPSIS
     ln [-Ffhinsv] source_file [target_file]
     ln [-Ffhinsv] source_file ... target_dir
     link source_file target_file
  • 创建软连接: ln -s <src> <new_link_dest>
  • 删除软连接: unlink <dest>

date

日期函数

常用选项:

  • date: 获取当前时间
  • date +%s: 获取当前时间,格式转成秒
  • date -d "+10 days": 当前时间10天后

cat

  • cat 1.txt>>2.txt: 将文件1.txt追加到文件2.txt

head

查看文件前面部分

  • head <file_name>: 查看 file_name 文件的前面部分,默认是10行
  • head -n15 <file_name>: 指定查看 file_name 的前15行
  • head <file_name_1> <file_name_2>: 查看 file_name_1 file_name_2 两个文件的前10行,其中文件的分类用==> file_name <==
  • head -c15 <file_name>: 查看 file_name 前15个字符,可以直接用k做单位, head -c 5k <file_name>
  • ls | head: 结合ls查看前面的对象,默认查看前10个, 可以结合ls的命令做出更加多元化的变化ls -lht | head查看最近的10个文件

tail

查看文件的结尾部分

# 查看文件倒数 100 行
tail -100 fileName.log
# 实时监听文件写入
tail -f file_name.log
# 查看文件的倒数 100 行 并实时监听
tail -100f fileName.log
  • 跳过文件的前面几行: 跳过前面2行tail -n +3 <filename>,跳过前面N行tail -n +$((x+1)) <filename>

sed

NAME
     sed -- stream editor
SYNOPSIS
     sed [-Ealn] command [file ...]
     sed [-Ealn] [-e command] [-f command_file] [-i extension] [file ...]

相关的option:

  • -n: By default, each line of input is echoed to the standard output after all of the commands have been applied to it. The -n option suppresses this behavior.

  • -i extension: Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.sed -i s/before/after/g FILE_NAME,如果是mac需要在在i后面增加一个空字符串sed -i '' s/before/after/g FILE_NAME

  • -f command_file: Append the editing commands found in the file command_file to the list of commands. The editing commands should each be listed on a separate line.

  • 查看文件除了前面几行: sed 1,Nd <file_name>

sed function

Sed Functions: 動作說明: [n1[,n2]]function n1, n2 : 選擇進行動作的行數,例如10,20[動作行為]

Sed function:

  • a: 新增,a 的後面可以接字串,這些字串會在目前的下一行出現
  • c: 取代,c 的後面可以接字串,這些字串可以取代 n1,n2之間的行
  • d: 刪除,d 後面通常不接任何字串
  • i: 插入,i 的後面可以接字串,這些字串會在目前的上一行出現
  • p: 列印,將某個選擇的資料印出.通常 p 會與參數 sed -n 一起運作
  • s: 取代,s 的動作可以搭配正規表示法.例如 1,20s/old/new/g

crontab

  • 列出crontab任务: crontab -l

  • 编辑crontab任务: crontab -e

  • crontab任务的一般格式:

    {minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script}
      minute: 区间为 0-59
      hour: 区间为0-23
      day-of-month: 区间为0-31
      month: 区间为1-12. 1是1月. 12是12月.
      day-of-week: 区间为0-7. 周日可以是0或7.
    # 1 0 * * * /root/bin/run.sh  每天00:01运行
    # 1 0 * * 1,2,3,4,5 /root/bin/run.sh  Mon-Fri的00:01运行
    # 1 0 * * 1-5 /root/bin/run.sh  Mon-Fri的00:01运行
    # */5 * * * * /root/bin/run.sh  每5分钟运行
    # @reboot 开机的时候运行

grep

grep, egrep, fgrep, rgrep - print lines matching a pattern

SYNOPSIS
       grep [OPTIONS] PATTERN [FILE...]
       grep [OPTIONS] [-e PATTERN]...  [-f FILE]...  [FILE...]
# 查找文件
grep 'test' jvm.log
# 多文件查找
grep 'test' jvm.log gc.log
# 在指定目录下查找所有符合关键字的文件 -r -n
grep 'test' /home/admin/ -r -n
# grep 中OR 匹配 \| : 注意转义
grep 'pattern1\|pattern2' jvm.log
grep '\(pattern1\|pattern2\)' jvm.log
# 查看不包括某个内容 -v
grep -v 'pattern' jvm.log

find

查找内容

  • -name: 查找名称

  • -iname: 查找后缀名

  • find . -name '.py': 查找文件夹下面所有py结尾的文件

  • find . -type f -iname '*.pdf': 查找当前文件夹下类型为文件,且扩展名是pdf的文件

  • find /path -name "*.py" -o -name "*.html": 查看路径下py结尾或者html结尾的文件

  • find . -name '.py' | xargs wc -l | sort -nr | head -n 30: 查看文件夹下py文件行数前30行数和相对路径

  • find /path -type d -ctime +10: 查看指定路径下创建时间是1天前的文件夹

sort

按照字段排序,默认第一个字段

  • -n, --numeric-sort: compare according to string numerical value,将内容看成数字,不然会出现 '99'>'999'的情况
  • -r, --reverse: reverse the result of comparisons
  • -k, --key=KEYDEF: sort via a key; KEYDEF gives location and type

相关的options为:

  • -i: --ignore-case 不区分大小写查找(默认区分大小写grep)
  • -A: --after-context=NUM 在匹配到的行里面向后查找行数grep -A <num> 'pattern' filename
  • -B: --before-context=NUM 在匹配到的行里面向前查找行数grep -B <num> 'pattern' filename
  • -C: --context=NUM 在匹配到的行里面前后查找行数grep -C <num> 'pattern' filename
  • -v: --invert-match 实现 NOT 操作grep -v 'not-in-pattern' filename
  • -E: --extended-regexp 扩展为正则表达式,此时可以直接用|实现or功能
  • -e: 实现 and 同一个行匹配多个项目
  • -r -R: --recursive --dereference-recursive 两个一般同时使用,查看目录多个文件的匹配结果,一般和-n一起用grep -rn 'pattern' /path/to/find
  • -c: --count 统计文本或者文件中匹配中的字符串数量grep -c 'pattern' filename
  • -n: --line-number 查看匹配中的行号 从1开始grep -n 'pattern' filename
  • -q: --quiet, --silent,静默输出如果命令运行成功返回0,失败则返回非0值.一般用于条件测试grep -q 'pattern' filename

shift

移动参数的位置shift 3会将原来的$4现在变成$1,示例代码如下

# $ cat x_shift
until [ $# -eq 0 ]; do
  echo "第一个参数为: $1 参数个数为: $#"
  shift
done

# $ ./x_shift.sh 1 2 3 4

# 结果显示如下:
# 第一个参数为: 1 参数个数为: 4
# 第一个参数为: 2 参数个数为: 3
# 第一个参数为: 3 参数个数为: 2
# 第一个参数为: 4 参数个数为: 1

top

display Linux tasks.输入了top之后可以进行如下操作

输入 说明
h 获取帮助信息 or ?
q 退出top监控页面 or ctrl + c
u 某一用户启动的所有进程
c 显示/取消,进程执行的详细信息,在COMMAND字段显示
k kill指定PID的进程
1(数字1) 列出所有的单个CPU负载情况
O 排序,设置排序字段;n:Mem,k:CPU
P 排序,按照CPU
M 排序,按照内存
T 排序,按照时间/累计时间
R 倒序;即,如果原来按从小到大排序,则,变为从大到小排序
Z top显示颜色 设置窗口颜色配置方案
x 类似高亮显示,在z显示模式下效果才会更明显
H 显示线程
W 保存当前top命令的设置
i 忽略闲置和僵尸进程
d 自定义top命令的刷新时间
shift </> 上下翻页
A 分类显示各种系统资源高的进程。可用于快速识别系统上的性能要求极高的任务,推荐使用

部分常见的解释:

  • %CPU: CPU Usage, The percentage of your CPU that is being used by the process. By default, top displays this as a percentage of a single CPUunderstanding-cpu-while-running-top-command. You can toggle this behavior by hitting Shift i while top is running to show the overall percentage of available CPUs in use.
  • %MEN: 该进程占用的物理内存占总内存的百分比

paste

将行数据拼接成一列数据

  • echo 'zhong\njia\njie' | paste -sd% -: 常规用法,将多行数据链接成一行数据,并通过%链接

  • 如果cat files.txt | xargs ls -l | cut -c 23-30返回的是

    151552
    319488
    1536000
    225280

    想要得到这列数据的和,... | paste -sd+ - | bc

chown

更改文件和文件夹拥有者

  • chown -R username:groupname directory: 更改directory目录所有文件和文件夹至用户username:groupname

chmod

更改文件夹读写权限

  • chmod 777 directory: 更改directory目录为777读写权限
  • chmod a+x directory: 更改directory目录为进入和执行权限

rsync

NAME
       rsync - a fast, versatile, remote (and local) file-copying tool
SYNOPSIS
       Local:  rsync [OPTION...] SRC... [DEST]

       Access via remote shell:
         Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
         Push: rsync [OPTION...] SRC... [USER@]HOST:DEST

       Access via rsync daemon:
         Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST]
               rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
         Push: rsync [OPTION...] SRC... [USER@]HOST::DEST
               rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST

       Usages with just one SRC arg and no DEST arg will list the source files instead of copying.
  • --exclude=build/: 排除指定路径,参考

eval

construct command by concatenating arguments,通过连接的方式来构造参数

foo=10
x=foo
y='$'$x
echo $y
$foo
eval y='$'$x
echo $y
10

test

测试条件是否成立

if test <condition>
then
    echo True
else
    echo false
fi

trap

trap [-lp] [[arg] sigspec ...]

The command arg is to be read and executed when the shell receives signal(s) sigspec.

这个在特殊情况非常有用,如果想要程序退出时运行一段函数,就可以按照How to run a command before a Bash script exits完成

  • trap <FUNCTION> EXIT: 设置在退出之前运行函数FUNCTION
  • trap '' EXIT: 将退出的回调函数置为空。如果设置了trap <FUNCTION> EXIT会导致全部的退出都会运行函数FUNCTION,如果遇到部分函数不需要退出时运行FUNCTION则使用这句,参考这里

解压压缩

What's the difference between .tar.gz and .gz, or .tar.7z and .7z中有关于各个压缩格式的区别,其中比较重要的两点是

  • windows里面归档(多个文件合成一个文件)和压缩是一起的,但是linux里面归档和压缩是分开的,tar只负责归档,gzip只负责压缩,所以要实现归档和压缩,就要先 tar 再 gzip,所以最后的文件是.tar.gz
  • 压缩比率排名tar.bz2>tar.gz>zip>tar,压缩率越高,压缩以及解压的时间也就越长

tar

tar是linux中最常用的归档命令.tar命令可用于处理后缀名为tar,tar.gz,tgz,tar.Z,tar.bz2的文件.这些包的特点是都是以tar归档,但是创建压缩文件的方式不一样

$ man tar
NAME
     tar -- manipulate tape archives

# 注意事项: `tar`所有的解压或者压缩都要带`-f`且放在最后,因为它指定了压缩包名字,否则会出现解压或压缩失败
SYNOPSIS
     tar [bundled-flags <args>] [<file> | <pattern> ...]
     tar {-c} [options] [files | directories]
     tar {-r | -u} -f archive-file [options] [files | directories]
     tar {-t | -x} [options] [patterns]

$ tar --help
tar(bsdtar): manipulate archive files
First option must be a mode specifier:
  -c Create  -r Add/Replace  -t List  -u Update  -x Extract
Common Options:
  -b #  Use # 512-byte records per I/O block
  -f <filename>  Location of archive
  -v    Verbose
  -w    Interactive
Create: tar -c [options] [<file> | <dir> | @<archive> | -C <dir> ]
  <file>, <dir>  add these items to archive
  -z, -j, -J, --lzma  Compress archive with gzip/bzip2/xz/lzma
  --format {ustar|pax|cpio|shar}  Select archive format
  --exclude <pattern>  Skip files that match pattern
  -C <dir>  Change to <dir> before processing remaining files
  @<archive>  Add entries from <archive> to output
List: tar -t [options] [<patterns>]
  <patterns>  If specified, list only entries that match
Extract: tar -x [options] [<patterns>]
  <patterns>  If specified, extract only entries that match
  -k    Keep (don't overwrite) existing files
  -m    Don't restore modification times
  -O    Write entries to stdout, don't restore to disk
  -p    Restore permissions (including ACLs, owner, file flags)
  • 解压文件: tar -xzvf tarball.tar.gz,这个是tar.gz文件,如果别的压缩类型就将-z参数替换成别的
    • 指定解压目录: tar -xzvf tarball.tar.gz -C /PATH/TO/TARGET
    • 仅解压指定的文件: tar -xzvf test.tar.gz log/1.log
    • 不覆盖以存在文件: -k
    • 去掉文件夹层数: tar -xzvf test.tar.gz --strip-components=1,strip NUMBER leading components from file names on extraction
  • 归档并压缩: tar -czvf test.tar.gz folder file *.log,支持文件夹,文件,正则表达式,增加了-z参数会将归档压缩.如果没有则只是做归档,归档不压缩占用的空间更大.这个是压缩成tar.gz包,如果需要压缩成别的则替换-z参数
    • 删除原文件: tar -czvf tarball.tar.gz file/folder && rm -rf file/folder
    • 除开指定文件: tar -czvf tarball.tar.gz --exclude=test/*.log test/*,打包test目录下所有文件,排除以.log结尾的文件
  • 查看压缩包中的文件: tar -tvf tarball.tar
  • 修改压缩包中的文件: tar -rvf tarball.tar file_name,向压缩包中增加/替换file_name文件
  • 删除压缩包中的文件: tar --delete -f tarball.tar file_name,删除tar包中的file_name文件/夹

gzip

# 解压
gzip -dv test.gz
gunzip < zipfile.gz > outputfile  # 更加通用的方法 Pass the file to gunzip as stdin
# Use zcat (or, on older systems, gzcat)
zcat file.gz > file

# 压缩 gzip对文本的压缩率约有60%~70%
gzip -k ./*          # 当前目录下所有文件进行压缩,每个文件一个gz包
gzip -rkv ./*        # 递归压缩

相关options:

  • -k, --keep: keep (don't delete) input files, after version 1.6
  • -d, --decompress: decompress
  • -r, --recursive: operate recursively on directories
  • -v, --verbose: verbose mode

zip/unzip

zip和unzip命令主要用于处理zip包

# 解压
unzip -l test.zip         # 可以看到压缩包中的文件名,日期等信息
unzip -v test.zip         # 查看更多信息,例如crc校验信息等
# 解压到指定目录
unzip -o test.zip -d dir  # 将test.zip解压到dir目录 并覆盖原来存在的文件
# 解压压缩包中的指定文件
unzip -o test.zip "1.log" -d dir   # 解压包中的1.log文件到dir目录
unzip -o tet.zip "*.log" -d dir    # 解压包中所有的log文件
# 解压jar包
unzip -o java.jar -d dir  # 解压jar包到指定目录

# 压缩文件
zip -r test.zip test/     # 打包test目录下的文件
zip -rj test.zip test/    # 打包test目录下文件,且压缩包不带test目录
# 指定压缩率打包文件
zip -r8 test.zip test/*   # 数值(1-9)越大,压缩率越高,耗时越长

# 向压缩包中增加或更新文件
zip -u test.zip test2     # 向test.zip 包中增加test2文件
# 删除压缩包的特定文件
zip -d test.zip test      # 删除test.zip包中的test文件

# 压缩时加密
zip -r test.zip test1 test -P 66666 # 使用密码66666加密

相关的option:

  • -r: recurse into directories
  • -j: junk (don't record) directory names
  • -o: overwrite files WITHOUT prompting

rar 包

# 解压 rar 包
unrar e file_name.rar   # 直接解压文件到当前文件夹
unrar x file_name.rar   # 解压文件夹保持原本的目录结构
unrar x file_name.rar /path/to/extract  # 保持原本的目录结构并解压到/path/to/extract目录

相关的option:

  • e: Extract files without archived paths
  • x: Extract files with full path
  • v[t[a],b]: Verbosely list archive contents [technical[all],bare]
  • p: Print file to stdout

FAQ

How to use find command to find all files with extensions from list

find /path/to -regex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

leetcode-195 获取一个文件的第十行

# 通过 sed pick 获取文件第十行(如果没有第十行会返回空)
sed -n "10p" file.txt

# 通过 head tail 获取文件第十行
tail -n +10 file.txt | head -1

leetcode-193 判断电话号码是否有效

有效的格式是 (xxx) xxx-xxxx 或者 xxx-xxx-xxxx

  • awk
    • awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt
    • awk '/(^[0-9]{3}-[0-9]{3}|^\([0-9]{3}\) [0-9]{3})-[0-9]{4}$/' file.txt
  • grep
    • egrep '^(\([0-9]{3}\)\ |[0-9]{3}-)[0-9]{3}-[0-9]{4}$' file.txt

本地运行远程服务器的命令

目前有两种方法,如果有变量需要从本机传输到远程的机器,建议使用方法二

  • 方法一,使用<< 'COMMAND'命令框起来,可是实现多级嵌套

    ssh user@host << 'ENDSSH'
    #commands to run on remote host
    ENDSSH
    
    # 多级嵌套
    ssh user@host <<-'ENDSSH'
      #commands to run on remote host
      ssh user@host2 <<-'END2'
          # Another bunch of commands on another host
          wall <<-'ENDWALL'
              Error: Out of cheese
          ENDWALL
          ftp ftp.secureftp-test.com <<-'ENDFTP'
              test
              test
              ls
          ENDFTP
      END2
    ENDSSH
  • 方法二,使用ssh -t方法运行远程命令

    ssh -t root@srv "
    # your command here
    "
    
    ssh -t root@srv "
    echo $HOST_VAR_COULD_BE_USE
    # your command here
    "

实现bash脚本遇到返回值非0时立马退出

详见这里,在shell脚本之前设置set -e即可,如果象牙更多的设置,使用set -euxo pipefail,bash-手册关于set部分有详细的说明,也可以看Safer bash scripts with 'set -euxo pipefail'

set -e
# 加上使用 && ||
  • -e: exits on error
  • -u: errors on undefined variables
  • -x: print each command before executing it
  • -o pipefail: exits on command pipe failures

怎么跳过文件的前面几行

  • 本篇tail有说明,使用tail -n +$((x+1)) <filename>跳过文件的前N行
  • 也可是使用sed: sed 1,Nd <filename>,如果是通过管道获取的数据,使用这个会更加方便

在命令行运行shell脚本中的函数

参照这里,在shell脚本后面增加"$@",运行函数的时候可以直接bash <SCRIPT_NAME>.sh <FUNCTION_NAME>

testA() {
  echo "TEST A $1";
}
testB() {
  echo "TEST B $2";
}
"$@"

编写shell时推荐使用env二进制文件

It is often recommended to use the env command in the shebang:

#!/usr/bin/env bash

The env command will determine the path to the bash binary in the current environment. (i.e. using the current PATH) This is useful when the script has to run in various environments where the location of the bash binary is unknown, in other words across multiple Unix and Unix-like platforms. However, this renders the actual version of bash that will interpret the script unpredictable.

更加高级的切换目录

pushd

  • pushd /path: 会将当前目录current_path/path目录放到一个虚拟堆栈中,通过dirs命令可以查看虚拟堆栈的情况
  • pushd: 在虚拟堆栈中顶部的两个堆栈进行切换,并将两个路径的位置调换顺序
  • pushd +n: 切换到指定目录中,n代表虚拟堆栈的编号,可以通过dirs查看编号.切换的方式是将虚拟堆栈逐一出栈,插入栈底,知道取出虚拟位置的路径为止

popd

  • popd: 将虚拟堆栈中的栈顶元素出栈
  • popd +n: 将虚拟堆栈中的指定位置的元素出栈,元素位置可以通过dirs查看编号

dirs

  • dirs: 查看虚拟堆栈的情况
  • dirs -p - v: 每行显示一个虚拟堆栈的路径情况,上面是栈顶,下面是栈底,并带上符号

查看端口是否被占用

  • netstat:
    • Linux: netstat -anp | grep <PORT>
    • MAC: netstat -an | grep <PORT>
  • lsof: lsof -i:<PROT>

列表的声明和遍历

这里

## declare an array variable
declare -a arr=("element1" "element2" "element3")

## now loop through the above array
for i in "${arr[@]}"
do
   echo "$i"
   # or do whatever with individual element of the array
done

# You can access them using echo "${arr[0]}", "${arr[1]}" also

列表转成指定字符串

参照这里,推荐使用的方法是

arr=('s1' 's2' 's3' 's4 4 4')
# %s\n" 可以换成对应的各个符号
printf -v var "%s\n" "${arr[@]}"

查看字符串是否另一个的子字符串

详见这里

string='My long string'
if [[ ${string} == *"My long"* ]]; then
  echo "It's there!"
fi

if..else if... else怎么写

这里

if [ "$seconds" -eq 0 ];then
   $timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
else
   echo "Unknown parameter"
fi

bash 日期格式化

这里

printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1

bash脚本解析参数

使用getopts或者getopt处理参数,详见这里

bash读取用户输入

这里

# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user

字符串大小写转化

这里

x="HELLO"
echo $x  # HELLO

y=${x,,}
echo $y  # hello

z=${y^^}
echo $z  # HELLO

切割字符串并获得最后一个字段

这里

echo 'maps.google.com' | awk -F. '{print $NF}'

bash脚本获得可选参数

这里

somecommand ${1:-foo}

查看字符串是否有换行

这里常用于从命令行获取参数,然后判断参数是否有多行,如docker ps -aq

if [[ "$myvar" = *$'\n'* ]]; then
    echo "multiple lines"
fi

⚠️ **GitHub.com Fallback** ⚠️