【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

相关文章

Spring 缓存在项目中的使用详解

《Spring缓存在项目中的使用详解》Spring缓存机制,Cache接口为缓存的组件规范定义,包扩缓存的各种操作(添加缓存、删除缓存、修改缓存等),本文给大家介绍Spring缓存在项目中的使用... 目录1.Spring 缓存机制介绍2.Spring 缓存用到的概念Ⅰ.两个接口Ⅱ.三个注解(方法层次)Ⅲ.

Spring Boot 整合 Redis 实现数据缓存案例详解

《SpringBoot整合Redis实现数据缓存案例详解》Springboot缓存,默认使用的是ConcurrentMap的方式来实现的,然而我们在项目中并不会这么使用,本文介绍SpringB... 目录1.添加 Maven 依赖2.配置Redis属性3.创建 redisCacheManager4.使用Sp

Spring Cache注解@Cacheable的九个属性详解

《SpringCache注解@Cacheable的九个属性详解》在@Cacheable注解的使用中,共有9个属性供我们来使用,这9个属性分别是:value、cacheNames、key、key... 目录1.value/cacheNames 属性2.key属性3.keyGeneratjavascriptor

PyTorch中cdist和sum函数使用示例详解

《PyTorch中cdist和sum函数使用示例详解》torch.cdist是PyTorch中用于计算**两个张量之间的成对距离(pairwisedistance)**的函数,常用于点云处理、图神经网... 目录基本语法输出示例1. 简单的 2D 欧几里得距离2. 批量形式(3D Tensor)3. 使用不

Python模拟串口通信的示例详解

《Python模拟串口通信的示例详解》pySerial是Python中用于操作串口的第三方模块,它支持Windows、Linux、OSX、BSD等多个平台,下面我们就来看看Python如何使用pySe... 目录1.win 下载虚www.chinasem.cn拟串口2、确定串口号3、配置串口4、串口通信示例5

Nginx 413修改上传文件大小限制的方法详解

《Nginx413修改上传文件大小限制的方法详解》在使用Nginx作为Web服务器时,有时会遇到客户端尝试上传大文件时返回​​413RequestEntityTooLarge​​... 目录1. 理解 ​​413 Request Entity Too Large​​ 错误2. 修改 Nginx 配置2.1

springboot项目redis缓存异常实战案例详解(提供解决方案)

《springboot项目redis缓存异常实战案例详解(提供解决方案)》redis基本上是高并发场景上会用到的一个高性能的key-value数据库,属于nosql类型,一般用作于缓存,一般是结合数据... 目录缓存异常实践案例缓存穿透问题缓存击穿问题(其中也解决了穿透问题)完整代码缓存异常实践案例Red

Java 的 Condition 接口与等待通知机制详解

《Java的Condition接口与等待通知机制详解》在Java并发编程里,实现线程间的协作与同步是极为关键的任务,本文将深入探究Condition接口及其背后的等待通知机制,感兴趣的朋友一起看... 目录一、引言二、Condition 接口概述2.1 基本概念2.2 与 Object 类等待通知方法的区别

Java List排序实例代码详解

《JavaList排序实例代码详解》:本文主要介绍JavaList排序的相关资料,Java排序方法包括自然排序、自定义排序、Lambda简化及多条件排序,实现灵活且代码简洁,文中通过代码介绍的... 目录一、自然排序二、自定义排序规则三、使用 Lambda 表达式简化 Comparator四、多条件排序五、

Java实例化对象的​7种方式详解

《Java实例化对象的​7种方式详解》在Java中,实例化对象的方式有多种,具体取决于场景需求和设计模式,本文整理了7种常用的方法,文中的示例代码讲解详细,有需要的可以了解下... 目录1. ​new 关键字(直接构造)​2. ​反射(Reflection)​​3. ​克隆(Clone)​​4. ​反序列化