【Cheatsheet】详解:shell script各种指令(含grep等)

2023-10-12 22:40

本文主要是介绍【Cheatsheet】详解:shell script各种指令(含grep等),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 前言
  • 文件夹操作
    • 如何得到脚本当前所在目录?
    • 遍历文件夹
  • 进程操作
    • 如何杀死一个进程?
  • 文件操作
    • 查找文件(文件查找)
    • shell读取json文件
    • 匹配指定后缀的文件
  • 字符串操作
    • 字符串相等比较
    • 首字母大写
    • 判断字符串最后是否为斜杠 /
    • 字符串截取(以及去掉斜杠)
  • 运算操作
    • shell相等、比较
    • shell 加法
  • 数据结构操作
    • shell保存为数组
  • 命令行操作
    • 检查java version
    • 多个指令 &
    • 命令行参数
      • 判断命令行参数个数
      • 脚本参数
  • 输出操作
    • shell格式化输出字符串
    • shell打印星号(*)
    • 2>&1的含义
    • 输出时间time
    • 将标准输出和错误输出都输出到日志
  • 语法结构(if之类)
    • shell的if语句(条件判断)
  • 各种指令
    • sed 指令
    • tr指令
  • 环境(软链接之类)
    • alias (修改~/.bashrc)
    • 修改软链接
    • ubuntu下通过软链接更换软件版本
    • 环境变量(export)
    • ubuntu 自定义指令
    • shell中的各种判断 以及 unary operator expected 报错解决
    • 定时运行指令
    • docker 下实现定时运行指令
    • 查找文本及文本中的内容 (find)
    • grep指令
      • 排除某个word来做搜索

前言

写了这么多脚本了,但是记录下来的却很少,导致每次要查,反复无用之功,实为可惜。故在此将一些有用的指令记下来,用于未来之查找。

创建时间:2019年04月10日 21:52:07

2020年10月11日20:53:38 更新一波。

文件夹操作

如何得到脚本当前所在目录?

BASE="$(cd $(dirname $0); pwd)"
其中,BASE的值就是当前目录的绝对路径。

参考:
Linux shell - dirname $0 定位到运行脚本的相对位置 https://www.cnblogs.com/recognition/p/5462824.html
此外还参考了 Defects4J的init.sh脚本。

遍历文件夹

project=(dir1 dir2 dir3)curDir="$(cd $(dirname $0);pwd)"for((i=0;i<${#project[*]};i++))
docd ${project[i]}for element in `ls`   #遍历文件夹doif [ -d "$element" ];then #判断是否为文件夹echo "The $element is a directory“fi#break  #done#cd -   #回到上一个工作文件夹cd $curDir#break
done

或者:

        for file in `ls $wd/lib/`doif [[ "$file" == *.jar ]]; thenclasspath=$classpath:$wd/lib/$filefidone

for file in ls $wd/lib/ 是关键

  • shell脚本编写遍历某一目录下的所有文件 ttps://www.cnblogs.com/lxyuuuuu/p/9895127.html

进程操作

如何杀死一个进程?

比如:我的gedit编辑器卡住了,现在我想杀死这个进程。

只需要:
pkill gedit 就行。

然后 pgrep gedit查看是否还存在这个进程。如果还是有,那么就 pkill -9 gedit

文件操作

查找文件(文件查找)

ubuntu下如何查找某个文件的路径 https://www.jianshu.com/p/8a59c24203db

find / -name xxx
whereis
locate

shell读取json文件

linux 命令之jq https://blog.csdn.net/u011641885/article/details/45559031
Linux下处理JSON的命令行工具:jq—安装 https://blog.csdn.net/Sunny_much/article/details/50668871
在Shell命令行处理JSON数据的方法 https://m.jb51.net/article/48017.htm
shell 解析 json https://www.cnblogs.com/lasclocker/p/5539467.html

匹配指定后缀的文件

if [[ "$file" == *.jar ]]; then
这个是关键。

    # modified on july 31th. by dale/classpath=""for file in `ls $wd/lib/`doif [[ "$file" == *.jar ]]; thenclasspath=$classpath:$wd/lib/$filefidoneif [ -f "$wd/build/lib/rhino.jar" ];thenclasspath=$classpath:$wd/build/lib/rhino.jarficlasspath=$bsrc:${btest}${classpath}echo "classpath for ${proj}_$id is: $classpath"

字符串操作

字符串相等比较

if [ "$VAR1" = "$VAR2" ]; then# 或者if [[ "$VAR1" == "$VAR2" ]]; then# 不相等
if [ "$VAR1" != "$VAR2" ]; then

参考:

  • How to Compare Strings in Bash https://linuxize.com/post/how-to-compare-strings-in-bash/

首字母大写

PID=chart
echo "${PID^}"  # 这时候的输出为Chart

判断字符串最后是否为斜杠 /

在这里插入图片描述

判断字符串最后是否为 斜杠 https://blog.csdn.net/m0_37962554/article/details/79882262

字符串截取(以及去掉斜杠)

Shell 字符串截取方法 https://blog.csdn.net/qq_33951180/article/details/68059098

shell 去掉字符串最后一个斜杠(如果最后一个字符是斜杠) https://blog.csdn.net/u013992330/article/details/79943601

在这里插入图片描述

shell去掉字符串最后一个字符 https://blog.csdn.net/chenghuikai/article/details/52447182

var=”12345467,” 
${var%?}=”1234567”

运算操作

shell相等、比较

if [ $x -eq 3 ]; then .....

也可参考:检查java version小节。

参考:

  • Check whether one number equals another number in Bash https://stackoverflow.com/questions/15867813/check-whether-one-number-equals-another-number-in-bash

shell 加法

((i=$j+$k))    等价于 i=`expr $j + $k`
((i=$j-$k))     等价于   i=`expr $j -$k`
((i=$j*$k))     等价于   i=`expr $j \*$k`
((i=$j/$k))     等价于   i=`expr $j /$k`

自加:
((n+=1))
((n++))

参考:
linux下的shell运算(加、减、乘、除 https://blog.csdn.net/hxpjava1/article/details/80719112

在这里插入图片描述

shell中十种实现自加的方法 https://blog.csdn.net/thy822/article/details/72599637

数据结构操作

shell保存为数组

在这里插入图片描述

shell 按行读取并保存成数组 https://blog.csdn.net/qq_26870933/article/details/83000264

命令行操作

检查java version

java -version 2>&1 | sed -n ';s/.* version "\(.*\)\.\(.*\)\..*".*/\1\2/p;'

或者:

JAVA_VER=$(java -version 2>&1 | sed -n ';s/.* version "\(.*\)\.\(.*\)\..*".*/\1\2/p;')
[ "$JAVA_VER" -ge 15 ] && echo "ok, java is 1.5 or newer" || echo "it's too old..."

参考:

  • Correct way to check Java version from BASH script https://stackoverflow.com/questions/7334754/correct-way-to-check-java-version-from-bash-script

多个指令 &

command1 & command2 & command3 三个命令同时执行 command1; command2; command3   不管前面命令执行成功没有,后面的命令继续执行 command1 && command2           只有前面命令执行成功,后面命令才继续执行

比如:
[ -d bin ] && echo "bin exists & now remove it" && rm -rf bin

参考:

  • Shell多个命令间隔符号;和&和&&区别 https://blog.51cto.com/kusorz/1963633

命令行参数

判断命令行参数个数

if [ $# != 1 ]; thenecho "USAGE: $0 file_name"exit 1;
fi

在这里插入图片描述
shell 如何判断命令行参数个数 https://blog.csdn.net/mick_ye/article/details/50259567

脚本参数

Shell 传递参数 https://www.runoob.com/linux/linux-shell-passing-arguments.html

proj=$1
id=$2
skipTest=$3
project="${proj^}"if [ $# -lt 2 ];
thenecho -e "\nparameter error. \nThe usage: ./single-download.sh <proj> <id> <optional:skipTest 1 or 0>"echo -e "e.g., ./single-download.sh  chart 3 1\n"exit
fi

输出操作

shell格式化输出字符串

Shell 格式化输出数字、字符串(printf) https://www.cnblogs.com/argor/p/7911146.html
printf打印格式字符串,解释'%'指令和'\'转义。

shell打印星号(*)

a=*
echo $a   #这只会输出当前文件夹下所有文件
echo "$a"   #这样才会输出*

shell中变量被定义为星号(*)后无法引用的问题 https://blog.51cto.com/leidongya/1588056

2>&1的含义

在这里插入图片描述

  • linux shell中"2>&1"含义 https://www.cnblogs.com/zhenghongxin/p/7029173.html

输出时间time

  • shell脚本实现取当前时间 https://www.cnblogs.com/janezhao/p/9732157.html
#!bin/bash
time4=$(date "+%Y.%m.%d")
echo $time4
time3=$(date "+%Y-%m-%d %H:%M:%S")

将标准输出和错误输出都输出到日志

也就是重定向。

<cmd> >log_file 2>&1

即可。
在这里插入图片描述

  • 如何获取shell命令输出的错误信息 https://zhidao.baidu.com/question/1898301748448840340.html
  • shell 中 标准输出和错误输出 https://www.cnblogs.com/37yan/p/7873626.html

语法结构(if之类)

shell的if语句(条件判断)

shell if https://blog.csdn.net/wojiuguowei/article/details/83625898

各种指令

sed 指令

示例:前面的检查java version小节。

参考:

  • Linux sed命令完全攻略(超级详细) c.biancheng.net/view/4028.html

tr指令

shell tr命令的使用 https://fyan.iteye.com/blog/1172279

环境(软链接之类)

alias (修改~/.bashrc)

alias cdrun='( cd "$HOME/somedir" && ./script.sh )'

备注:注意括号,以及&&的使用。

参考:

  • Alias to CD in a directory and call a command https://unix.stackexchange.com/questions/366009/alias-to-cd-in-a-directory-and-call-a-command

修改软链接

  • ubuntu修改软链接 https://blog.csdn.net/u012897374/article/details/79199336

在这里插入图片描述

ubuntu下通过软链接更换软件版本

在这里插入图片描述

在这里插入图片描述

环境变量(export)

  • [1] EnvironmentVariables https://help.ubuntu.com/community/EnvironmentVariables
  • [2] Ubuntu设置和查看环境变量 https://blog.csdn.net/qq_32320399/article/details/80260856

设置环境变量有三种方式:
1)export
2)~/.bashrc
3)/etc/profile

取消环境变量请参考:
[1]
[2]

大概就是 export env_name= (等号右边没有值,为空。)
或者unset env_name

ubuntu 自定义指令

Ubuntu16.04下自定义命令 https://www.cnblogs.com/52-qq/p/8882075.html

nano ~/.bashrc,添加:

alias dc='docker exec -it -u deheng'

shell中的各种判断 以及 unary operator expected 报错解决

shell中的判断请参考如下,非常之详细,无怪乎有数万访问量,很厉害:

  • Shell if 条件判断 https://blog.csdn.net/zhan570556752/article/details/80399154
    在这里插入图片描述

在这里插入图片描述

佩服。


unary operator expected问题常常是因为在if判定的时候,=的左边或右边的值为空时导致的。
这时候给变量值加引号就行""

  • Shell脚本报错unary operator expected https://www.cnblogs.com/Cherie/p/3200294.html
  • shell脚本报错:"[: =: unary operator expected" https://blog.csdn.net/goodlixueyong/article/details/6564591
#----------------------------------------------------------------
flag="0"if [ "$skipTest" = "" ] || [ "$skipTest" = $flag ];thenecho "test now."cd ${wd}defects4j compiledefects4j test | tee > testInfo.txtcd -
elseecho "skip tests. Exit now."exit
fi

定时运行指令

关键词:shell timeout command
ubuntu python3 timeout for cmd

timeout 5 /path/to/slow/command with options
#以秒为单位。
  • Timeout a command in bash without unnecessary delay https://stackoverflow.com/questions/687948/timeout-a-command-in-bash-without-unnecessary-delay
  • Linux timeout Command Explained for Beginners (with Examples) https://www.howtoforge.com/linux-timeout-command/

本来想在python下搞,

  • Using module ‘subprocess’ with timeout https://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout
    但是好像不太顶用。

docker 下实现定时运行指令

最后没成功。但是也记录下吧。

  • Using cron in Docker containers ( Kubernetes ) https://esc.sh/blog/cron-jobs-in-docker/
  • Restarting cron after changing crontab file? https://stackoverflow.com/questions/10193788/restarting-cron-after-changing-crontab-file
  • docker-cron/Dockerfile https://github.com/Ekito/docker-cron/blob/master/Dockerfile
  • How to Run Cron Jobs inside Docker Containers https://medium.com/@jonbaldie/how-to-run-cron-jobs-inside-docker-containers-26964315b582
  • How to run a cron job inside a docker container? https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container

查找文本及文本中的内容 (find)

2019年8月17日14:29:40

  • [shell 命令] find 查找文件 https://www.cnblogs.com/surimj/p/9909502.html
find . -name *.txt | xargs grep "text_your_want_to_search"

grep指令

排除某个word来做搜索

参考:

  • How can I exclude one word with grep? https://stackoverflow.com/questions/4538253/how-can-i-exclude-one-word-with-grep
grep -P '(?!.*unwanted_word)keyword' file

我的场景:

grep -P '(?!.*Errors: 0)Errors:' *

这个的含义是:包含Errors:,但是不包含Errors: 0

grep -v不是很好用,特别是keyword和unwanted_word

这篇关于【Cheatsheet】详解:shell script各种指令(含grep等)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/198937

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected