【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

相关文章

Java中有什么工具可以进行代码反编译详解

《Java中有什么工具可以进行代码反编译详解》:本文主要介绍Java中有什么工具可以进行代码反编译的相关资,料,包括JD-GUI、CFR、Procyon、Fernflower、Javap、Byte... 目录1.JD-GUI2.CFR3.Procyon Decompiler4.Fernflower5.Jav

golang panic 函数用法示例详解

《golangpanic函数用法示例详解》在Go语言中,panic用于触发不可恢复的错误,终止函数执行并逐层向上触发defer,最终若未被recover捕获,程序会崩溃,recover用于在def... 目录1. panic 的作用2. 基本用法3. recover 的使用规则4. 错误处理建议5. 常见错

pycharm远程连接服务器运行pytorch的过程详解

《pycharm远程连接服务器运行pytorch的过程详解》:本文主要介绍在Linux环境下使用Anaconda管理不同版本的Python环境,并通过PyCharm远程连接服务器来运行PyTorc... 目录linux部署pytorch背景介绍Anaconda安装Linux安装pytorch虚拟环境安装cu

一文详解如何在Python中使用Requests库

《一文详解如何在Python中使用Requests库》:本文主要介绍如何在Python中使用Requests库的相关资料,Requests库是Python中常用的第三方库,用于简化HTTP请求的发... 目录前言1. 安装Requests库2. 发起GET请求3. 发送带有查询参数的GET请求4. 发起PO

Python进行PDF文件拆分的示例详解

《Python进行PDF文件拆分的示例详解》在日常生活中,我们常常会遇到大型的PDF文件,难以发送,将PDF拆分成多个小文件是一个实用的解决方案,下面我们就来看看如何使用Python实现PDF文件拆分... 目录使用工具将PDF按页数拆分将PDF的每一页拆分为单独的文件将PDF按指定页数拆分根据页码范围拆分

Java中的Cursor使用详解

《Java中的Cursor使用详解》本文介绍了Java中的Cursor接口及其在大数据集处理中的优势,包括逐行读取、分页处理、流控制、动态改变查询、并发控制和减少网络流量等,感兴趣的朋友一起看看吧... 最近看代码,有一段代码涉及到Cursor,感觉写法挺有意思的。注意是Cursor,而不是Consumer

javaScript在表单提交时获取表单数据的示例代码

《javaScript在表单提交时获取表单数据的示例代码》本文介绍了五种在JavaScript中获取表单数据的方法:使用FormData对象、手动提取表单数据、使用querySelector获取单个字... 方法 1:使用 FormData 对象FormData 是一个方便的内置对象,用于获取表单中的键值

前端知识点之Javascript选择输入框confirm用法

《前端知识点之Javascript选择输入框confirm用法》:本文主要介绍JavaScript中的confirm方法的基本用法、功能特点、注意事项及常见用途,文中通过代码介绍的非常详细,对大家... 目录1. 基本用法2. 功能特点①阻塞行为:confirm 对话框会阻塞脚本的执行,直到用户作出选择。②

SpringBoot项目注入 traceId 追踪整个请求的日志链路(过程详解)

《SpringBoot项目注入traceId追踪整个请求的日志链路(过程详解)》本文介绍了如何在单体SpringBoot项目中通过手动实现过滤器或拦截器来注入traceId,以追踪整个请求的日志链... SpringBoot项目注入 traceId 来追踪整个请求的日志链路,有了 traceId, 我们在排

HTML5中下拉框<select>标签的属性和样式详解

《HTML5中下拉框<select>标签的属性和样式详解》在HTML5中,下拉框(select标签)作为表单的重要组成部分,为用户提供了一个从预定义选项中选择值的方式,本文将深入探讨select标签的... 在html5中,下拉框(<select>标签)作为表单的重要组成部分,为用户提供了一个从预定义选项中