【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中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

前端CSS Grid 布局示例详解

《前端CSSGrid布局示例详解》CSSGrid是一种二维布局系统,可以同时控制行和列,相比Flex(一维布局),更适合用在整体页面布局或复杂模块结构中,:本文主要介绍前端CSSGri... 目录css Grid 布局详解(通俗易懂版)一、概述二、基础概念三、创建 Grid 容器四、定义网格行和列五、设置行

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

《Node.js数据库CRUD项目示例详解(完美解决方案)》:本文主要介绍Node.js数据库CRUD项目示例详解(完美解决方案),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考... 目录项目结构1. 初始化项目2. 配置数据库连接 (config/db.js)3. 创建模型 (models/

SQL表间关联查询实例详解

《SQL表间关联查询实例详解》本文主要讲解SQL语句中常用的表间关联查询方式,包括:左连接(leftjoin)、右连接(rightjoin)、全连接(fulljoin)、内连接(innerjoin)、... 目录简介样例准备左外连接右外连接全外连接内连接交叉连接自然连接简介本文主要讲解SQL语句中常用的表

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

SpringShell命令行之交互式Shell应用开发方式

《SpringShell命令行之交互式Shell应用开发方式》本文将深入探讨SpringShell的核心特性、实现方式及应用场景,帮助开发者掌握这一强大工具,具有很好的参考价值,希望对大家有所帮助,如... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定

Python中局部变量和全局变量举例详解

《Python中局部变量和全局变量举例详解》:本文主要介绍如何通过一个简单的Python代码示例来解释命名空间和作用域的概念,它详细说明了内置名称、全局名称、局部名称以及它们之间的查找顺序,文中通... 目录引入例子拆解源码运行结果如下图代码解析 python3命名空间和作用域命名空间命名空间查找顺序命名空

SpringRetry重试机制之@Retryable注解与重试策略详解

《SpringRetry重试机制之@Retryable注解与重试策略详解》本文将详细介绍SpringRetry的重试机制,特别是@Retryable注解的使用及各种重试策略的配置,帮助开发者构建更加健... 目录引言一、SpringRetry基础知识二、启用SpringRetry三、@Retryable注解