linux shell 入门学习笔记2shell脚本
什么是shell脚本
当命令或者程序语句写在文件中,我们执行文件,读取其中的代码,这个程序就称之为shell脚本。
有了shell脚本肯定是要有对应的解释器了,常见的shell脚本解释器有sh、python、perl、tcl、php、ruby等。一般这种使用文件方式来执行sh命令的方式被称为非交互方式。
- Windows中存在的*.bat批处理脚本。
- Linux中常用*.sh脚本文件。
shell脚本规则
在Linux系统中,shell脚本或者称之为bash shell程序,通常都是vim编辑,有Linux命令、bash shell指令、逻辑控制语句和注释信息组成。
google bash编程规范链接
- 1.使用.sh这样特定语言后缀作为扩展名,可以快速识别文件。
- 2.set可以设置shell的选项。SUID(Set User ID)和SGID(Set Group ID)在shell脚本中是被禁止的,如果你需要较高权限的访问请使用
sudo
。 - 3.建议使用
STDERR
打印错误信息。
err() {echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $@" >&2
}if ! do_something; thenerr "Unable to do_something"exit "${E_DID_NOTHING}"
fi
- 4.文件头:指定脚本解释器,这里是用#!/bin/bash做解释器的。
#!/bin/bash
#
# Perform hot backups of Oracle databases.
- 5.函数注释应该包括:
- 函数的描述
- 全局变量的使用和修改
- 使用的参数说明
- 返回值,而不是上一条命令运行后默认的退出状态
例如:
#!/bin/bash
#
# Perform hot backups of Oracle databases.export PATH='/usr/xpg4/bin:/usr/bin:/opt/csw/bin:/opt/goog/bin'#######################################
# Cleanup files from the backup dir
# Globals:
# BACKUP_DIR
# ORACLE_SID
# Arguments:
# None
# Returns:
# None
#######################################
cleanup() {...
}
- 6.TODO注释应该包含全部大写的字符串TODO,接着是括号中你的用户名。冒号是可选的。最好在TODO条目之后加上 bug或者ticket 的序号。
# TODO(mrmonkey): Handle the unlikely edge cases (bug ####)
- 7.缩进一般使用两个空格,没有制表符。
- 8.行的长度和长字符串最大长度为
80
个字符。
使用下述两种方式规避长字符串:
# DO use 'here document's
cat <<END;
I am an exceptionally long
string.
END# Embedded newlines are ok too
long_string="I am an exceptionallylong string."
- 9.管道尽量写在一行,否则应该将整个管道操作分割成每行一个管段,管道操作的下一部分应该将管道符放在新行并且缩进
2
个空格。这适用于使用管道符’|’的合并命令链以及使用’||’和’&&’的逻辑运算链。
# All fits on one line
command1 | command2# Long commands
command1 \| command2 \| command3 \| command4
- 10.循环中,
; do
,; then
应该和if/for/while
放在同一行。else
应该单独一行,结束语句应该单独一行并且跟开始语句垂直对齐。
例如:
for dir in ${dirs_to_cleanup}; doif [[ -d "${dir}/${ORACLE_SID}" ]]; thenlog_date "Cleaning up old files in ${dir}/${ORACLE_SID}"rm "${dir}/${ORACLE_SID}/"*if [[ "$?" -ne 0 ]]; thenerror_messagefielsemkdir -p "${dir}/${ORACLE_SID}"if [[ "$?" -ne 0 ]]; thenerror_messagefifi
done
- 11.case语句模式表达式前面不应该出现左括号。避免使用
;&
和;;&
符号。关键规则如下:
* 通过2
个空格缩进可选项。
* 在同一行可选项的模式右圆括号之后和结束符;;
之前各需要一个空格。
* 长可选项或者多命令可选项应该被拆分成多行,模式、操作和结束符;;
在不同的行。
例子1:
case "${expression}" ina)variable="..."some_command "${variable}" "${other_expr}" ...;;absolute)actions="relative"another_command "${actions}" "${other_expr}" ...;;*)error "Unexpected expression '${expression}'";;
esac
例子2:
verbose='false'
aflag=''
bflag=''
files=''
while getopts 'abf:v' flag; docase "${flag}" ina) aflag='true' ;;b) bflag='true' ;;f) files="${OPTARG}" ;;v) verbose='true' ;;*) error "Unexpected option ${flag}" ;;esac
done
- 12.变量扩展应该保持跟你所发现的一致,引用你的变量,推荐用
${var}
而不是$var
例如:
# Section of recommended cases.# Preferred style for 'special' variables:
echo "Positional: $1" "$5" "$3"
echo "Specials: !=$!, -=$-, _=$_. ?=$?, #=$# *=$* @=$@ \$=$$ ..."# Braces necessary:
echo "many parameters: ${10}"# Braces avoiding confusion:
# Output is "a0b0c0"
set -- a b c
echo "${1}0${2}0${3}0"# Preferred style for other variables:
echo "PATH=${PATH}, PWD=${PWD}, mine=${some_var}"
while read f; doecho "file=${f}"
done < <(ls -l /tmp)# Section of discouraged cases# Unquoted vars, unbraced vars, brace-quoted single letter
# shell specials.
echo a=$avar "b=$bvar" "PID=${$}" "${1}"# Confusing use: this is expanded as "${1}0${2}0${3}0",
# not "${10}${20}${30}
set -- a b c
echo "$10$20$30"
- 13.引用
- 除非需要小心不带引用的扩展,否则总是引用包含变量、命令替换符、空格或shell元字符的字符串
- 推荐引用是单词的字符串(而不是命令选项或者路径名)
- 千万不要引用整数
- 注意
[[
中模式匹配的引用规则 - 请使用
$@
除非你有特殊原因需要使用$*
例如:
# 'Single' quotes indicate that no substitution is desired.
# "Double" quotes indicate that substitution is required/tolerated.# Simple examples
# "quote command substitutions"
flag="$(some_command and its args "$@" 'quoted separately')"# "quote variables"
echo "${flag}"# "never quote literal integers"
value=32
# "quote command substitutions", even when you expect integers
number="$(generate_number)"# "prefer quoting words", not compulsory
readonly USE_INTEGER='true'# "quote shell meta characters"
echo 'Hello stranger, and well met. Earn lots of $$$'
echo "Process $$: Done making \$\$\$."# "command options or path names"
# ($1 is assumed to contain a value here)
grep -li Hugo /dev/null "$1"# Less simple examples
# "quote variables, unless proven false": ccs might be empty
git send-email --to "${reviewers}" ${ccs:+"--cc" "${ccs}"}# Positional parameter precautions: $1 might be unset
# Single quotes leave regex as-is.
grep -cP '([Ss]pecial|\|?characters*)$' ${1:+"$1"}# For passing on arguments,
# "$@" is right almost everytime, and
# $* is wrong almost everytime:
#
# * $* and $@ will split on spaces, clobbering up arguments
# that contain spaces and dropping empty strings;
# * "$@" will retain arguments as-is, so no args
# provided will result in no args being passed on;
# This is in most cases what you want to use for passing
# on arguments.
# * "$*" expands to one argument, with all args joined
# by (usually) spaces,
# so no args provided will result in one empty string
# being passed on.
# (Consult 'man bash' for the nit-grits ;-)set -- 1 "2 two" "3 three tres"; echo $# ; set -- "$*"; echo "$#, $@")
set -- 1 "2 two" "3 three tres"; echo $# ; set -- "$@"; echo "$#, $@")
- 14.命令替换应使用
$(command)
而不是反引号
# This is preferred:
var="$(command "$(command1)")"# This is not:
var="`command \`command1\``"
- 15.test, [和[[时,推荐使用
[[ ... ]]
,而不是[
,test
, 和/usr/bin/[
# This ensures the string on the left is made up of characters in the
# alnum character class followed by the string name.
# Note that the RHS should not be quoted here.
# For the gory details, see
# E14 at http://tiswww.case.edu/php/chet/bash/FAQ
if [[ "filename" =~ [^[:digit:]]+name ]]; thenecho "Match"
fi# This matches the exact pattern "f*" (Does not match in this case)
if [[ "filename" == "f*" ]]; thenecho "Match"
fi# This gives a "too many arguments" error as f* is expanded to the
# contents of the current directory
if [ "filename" == f* ]; thenecho "Match"
fi
- 16.测试字符串尽可能使用引用,而不是过滤字符串
例子1
# Do this:
if [[ "${my_var}" = "some_string" ]]; thendo_something
fi# -z (string length is zero) and -n (string length is not zero) are
# preferred over testing for an empty string
if [[ -z "${my_var}" ]]; thendo_something
fi# This is OK (ensure quotes on the empty side), but not preferred:
if [[ "${my_var}" = "" ]]; thendo_something
fi# Not this:
if [[ "${my_var}X" = "some_stringX" ]]; thendo_something
fi
例子2
# Use this
if [[ -n "${my_var}" ]]; thendo_something
fi# Instead of this as errors can occur if ${my_var} expands to a test
# flag
if [[ "${my_var}" ]]; thendo_something
fi
- 17.文件名的通配符扩展,当进行文件名的通配符扩展时,请使用明确的路径
# Here's the contents of the directory:
# -f -r somedir somefile# This deletes almost everything in the directory by force
psa@bilby$ rm -v *
removed directory: `somedir'
removed `somefile'# As opposed to:
psa@bilby$ rm -v ./*
removed `./-f'
removed `./-r'
rm: cannot remove `./somedir': Is a directory
removed `./somefile'
- 18.Eval应该避免使用
eval简单例子
# What does this set?
# Did it succeed? In part or whole?
eval $(set_my_variables)# What happens if one of the returned values has a space in it?
variable="$(eval some_function)"
- 19.不建议管道导向while循环
- 20.函数名,使用小写字母,并用下划线分隔单词。使用双冒号 :: 分隔库。函数名之后必须有圆括号。关键词 function 是可选的,但必须在一个项目中保持一致
# Single function
my_func() {...
}# Part of a package
mypackage::my_func() {...
}
当函数名后存在 () 时,关键词 function 是多余的。但是其促进了函数的快速辨识。
- 21.变量名,如函数名命名相同,循环的变量名应该和循环的任何变量同样命名
for zone in ${zones}; dosomething_with "${zone}"
done
- 22.常量和环境变量名,全部大写,用下划线分隔,声明在文件的顶部
# Constant
readonly PATH_TO_FILES='/some/path'# Both constant and environment
declare -xr ORACLE_SID='PROD'
动态生成的常量,可以使用readonly
和 export
来进行设置,在函数中declare
不会对全局变量进行操作。
VERBOSE='false'
while getopts 'v' flag; docase "${flag}" inv) VERBOSE='true' ;;esac
done
readonly VERBOSE
- 23.源文件名使用小写,如果需要的话使用下划线分隔单词
- 24.只读变量使用
readonly
或者declare -r
来确保变量只读
zip_version="$(dpkg --status zip | grep Version: | cut -d ' ' -f 2)"
if [[ -z "${zip_version}" ]]; thenerror_message
elsereadonly zip_version
fi
- 25.本地变量使用
local
声明特定功能的变量。声明和赋值应该在不同行。local
作用域为函数内部和子函数中可见。
my_func2() {local name="$1"# Separate lines for declaration and assignment:local my_varmy_var="$(my_func)" || return# DO NOT do this: $? contains the exit code of 'local', not my_funclocal my_var="$(my_func)"[[ $? -eq 0 ]] || return...
}
- 26.函数位置:将文件中所有的函数一起放在常量下面。不要在函数之间隐藏可执行代码
- 27.主函数main:为了方便查找程序的开始,将主程序放入一个称为 main 的函数,作为最下面的函数
- 28.检查返回值:使用 $? 或直接通过一个 if 语句来检查以保持其简洁
例子1
if ! mv "${file_list}" "${dest_dir}/" ; thenecho "Unable to move ${file_list} to ${dest_dir}" >&2exit "${E_BAD_MOVE}"
fi# Or
mv "${file_list}" "${dest_dir}/"
if [[ "$?" -ne 0 ]]; thenecho "Unable to move ${file_list} to ${dest_dir}" >&2exit "${E_BAD_MOVE}"
fi
例子2(Bash内部PIPESTATUS
变量)
-作用
tar -cf - ./* | ( cd "${dir}" && tar -xf - )
if [[ "${PIPESTATUS[0]}" -ne 0 || "${PIPESTATUS[1]}" -ne 0 ]]; thenecho "Unable to tar files to ${dir}" >&2
fi
例子3(PIPESTATUS
优化)
tar -cf - ./* | ( cd "${DIR}" && tar -xf - )
return_codes=(${PIPESTATUS[*]})
if [[ "${return_codes[0]}" -ne 0 ]]; thendo_something
fi
if [[ "${return_codes[1]}" -ne 0 ]]; thendo_something_else
fi
- 29.内建命令和外部命令选择上请使用内建命令
# Prefer this:
addition=$((${X} + ${Y}))
substitution="${string/#foo/bar}"# Instead of this:
addition="$(expr ${X} + ${Y})"
substitution="$(echo "${string}" | sed -e 's/^foo/bar/')"
相关文章:
linux shell 入门学习笔记2shell脚本
什么是shell脚本 当命令或者程序语句写在文件中,我们执行文件,读取其中的代码,这个程序就称之为shell脚本。 有了shell脚本肯定是要有对应的解释器了,常见的shell脚本解释器有sh、python、perl、tcl、php、ruby等。一般这种使用文…...

Android稳定性系列-01-使用 Address Sanitizer检测原生代码中的内存错误
前言想必大家曾经被各种Native Crash折磨过,本地测试没啥问题,一到线上或者自动化测试就出现各种SIGSEGV、SIGABRT、SIGILL、SIGBUS、SIGFPE异常,而且堆栈还是崩溃到libc.so这种,看起来跟我们的代码没啥关系,关键还不好…...
HyperOpt-quniform 范围问题
在使用 quniform 的时候,可能会出现超出指定范围的值,例如对于 GBDT 设置参数空间为 learning_rate:hp.quniform(learning_rate,0.05,2.05,0.2),但是仍然会报错 ValueError: learning_rate must be greater than 0 but was 0.0,但…...

Pycharm搭建一个Django项目
File->new project 点击create, 等待一下即可 查看安装 Django 版本: 在 Pycharm 底部选择 Terminal 然后在里面输入:python -m django --version 启动项目: 在 Terminal 里面输入: python manage.py runserver 查看文件目…...
浅析前端工程化中的一部曲——模块化
在日益复杂和多元的 Web 业务背景下,前端工程化经常会被提及。工程化的目的是高性能、稳定性、可用性、可维护性、高效协同,只要是以这几个角度为目标所做的操作,都可成为工程化的一部分。工程化是软件工程中的一种思想,当下的工程…...

新版bing(集成ChatGPT)申请通过后在谷歌浏览器(Chrome)上的使用方法
大家好,我是herosunly。985院校硕士毕业,现担任算法研究员一职,热衷于机器学习算法研究与应用。曾获得阿里云天池比赛第一名,科大讯飞比赛第三名,CCF比赛第四名。拥有多项发明专利。对机器学习和深度学习拥有自己独到的见解。曾经辅导过若干个非计算机专业的学生进入到算法…...

Time-distributed 的理解
前言 今天看到论文中用到 Time-distributed CNN,第一次见到 Time-distributed,不理解是什么含义,看到代码实现也很懵。不管什么网络结构,外面都能套一个TimeDistributed。看了几个博客,还是不明白,问了问C…...
matlab 计算矩阵的Moore-Penrose 伪逆
目录 一、Moore-Penrose 伪逆1、主要函数2、输入输出参数二、代码示例使用伪逆求解线性方程组一、Moore-Penrose 伪逆 Moore-Penrose 伪逆是一种矩阵,可在不存在逆矩阵的情况下作为逆矩阵的部分替代。此矩阵常被用于求解没有唯一解或有许多解的线性方程组。 对于任何矩阵…...
简历制作方面的经验与建议
专栏推荐:2023 数字IC设计秋招复盘——数十家公司笔试题、面试实录 专栏首页:2023 数字IC设计秋招复盘——数十家公司笔试题、面试实录 专栏内容: 笔试复盘篇 2023秋招过程中整理的笔试题,来源包括我自己求职笔试以及整理其他同学的笔试。包含华为、中兴、联发科、AMD、大…...
C语言--static、const、volatile关键字
Static static修饰局部变量改变了变量的生命周期,让静态局部变量出了作用域依然存在,到程序结束,生命周期才结束。 static 修饰局部变量 改变局部变量的生命周期,本质上是改变了局部变量的存储位置,让局部变量不再是…...
Rust学习入门--【18】Rust结构体
系列文章目录 Rust 语言是一种高效、可靠的通用高级语言,效率可以媲美 C / C 。本系列文件记录博主自学Rust的过程。欢迎大家一同学习。 Rust学习入门–【1】引言 Rust学习入门–【2】Rust 开发环境配置 Rust学习入门–【3】Cargo介绍 Rust学习入门–【4】Rust 输…...

LeetCode142 环形链表Ⅱ
题目: 给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评…...
JavaScript刷LeetCode拿offer-高频链表题
首先需要了解链表的概念 先把 next 记录下来 无论是插入,删除,还是翻转等等操作,先把 next 指针用临时变量保存起来,这可以解决 90% 重组链表中指向出错的问题, 如果不知道什么时候需要用到守卫,那就都用…...

linux系统编程2--网络编程
在linux系统编程中网络编程是使用socket(套接字),socket这个词可以表示很多概念:在TCP/IP协议中,“IP地址TCP或UDP端口号”唯一标识网络通讯中的一个进程,“IP地址端口号”就称为socket。在TCP协议中&#…...

Allegro如何重命名光绘操作指导
Allegro如何重命名光绘操作指导 在做PCB设计的时候,光绘设置是输出生产文件必要的流程,设置好光绘之后,如何对光绘重新命名,如下图 如何把L1改成TOP,L6改成BOTTOM,具体操作步骤如下 点击Manufacture选择Artwork...
[PMLR 2018] Hyperbolic entailment cones for learning hierarchical embeddings
Contents IntroductionEntailment Cones in the Poincar BallConvex cones in a complete Riemannian manifoldAngular cones in the Poincar ballfour intuitive propertiesClosed form expression of the optimal ψ \psi...

2023春季露营投影怎么选?轻薄投影极米Z6X Pro值得推荐
近年来,露营经济在多重因素的共同助推下快速发展,精致露营的攻略开始占据小红书、微博、朋友圈等各类社交平台,吸引着更多用户种草并加入到露营大军中,而露营经济的强势“破圈”给家用智能投影带来了更多的发展契机。凭借着小巧的…...

收藏,核心期刊的投稿、审稿、出刊流程详解
学术期刊论文(核心和普刊)的发表流程总的来说其实是一样的,整个流程包括:1写作-2选择刊物-3投稿-4审稿-5返修或拒稿-6录用-7出刊-8上网检索。 其中1和2其实顺序是可以调换的,可以选择好刊物再写作,根据刊物…...

JVM类加载子系统
1、类加载子系统在内存结构中所处的位置通过内存结构图,我们先知道类加载子系统所处的位置,做到心中有图。2、类加载器作用类加载器子系统负责从文件系统或者网络中加载Class文件,class文件在文件开头有特定的文件标识。ClassLoader只负责cla…...

摄像头的镜头的几个知识点
1、镜头的组成及镜片的固定方式 摄像头的镜头结构主要分为镜身,透镜,变焦环,对焦环,光圈叶片,部分还有防抖系统.其中最重要的就是透镜,也叫镜片。镜片的主要原料是光学玻璃,玻璃&…...

Chapter03-Authentication vulnerabilities
文章目录 1. 身份验证简介1.1 What is authentication1.2 difference between authentication and authorization1.3 身份验证机制失效的原因1.4 身份验证机制失效的影响 2. 基于登录功能的漏洞2.1 密码爆破2.2 用户名枚举2.3 有缺陷的暴力破解防护2.3.1 如果用户登录尝试失败次…...
DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径
目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...
Admin.Net中的消息通信SignalR解释
定义集线器接口 IOnlineUserHub public interface IOnlineUserHub {/// 在线用户列表Task OnlineUserList(OnlineUserList context);/// 强制下线Task ForceOffline(object context);/// 发布站内消息Task PublicNotice(SysNotice context);/// 接收消息Task ReceiveMessage(…...

边缘计算医疗风险自查APP开发方案
核心目标:在便携设备(智能手表/家用检测仪)部署轻量化疾病预测模型,实现低延迟、隐私安全的实时健康风险评估。 一、技术架构设计 #mermaid-svg-iuNaeeLK2YoFKfao {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg…...
线程同步:确保多线程程序的安全与高效!
全文目录: 开篇语前序前言第一部分:线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分:synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分ÿ…...
JVM暂停(Stop-The-World,STW)的原因分类及对应排查方案
JVM暂停(Stop-The-World,STW)的完整原因分类及对应排查方案,结合JVM运行机制和常见故障场景整理而成: 一、GC相关暂停 1. 安全点(Safepoint)阻塞 现象:JVM暂停但无GC日志,日志显示No GCs detected。原因:JVM等待所有线程进入安全点(如…...

听写流程自动化实践,轻量级教育辅助
随着智能教育工具的发展,越来越多的传统学习方式正在被数字化、自动化所优化。听写作为语文、英语等学科中重要的基础训练形式,也迎来了更高效的解决方案。 这是一款轻量但功能强大的听写辅助工具。它是基于本地词库与可选在线语音引擎构建,…...
IP如何挑?2025年海外专线IP如何购买?
你花了时间和预算买了IP,结果IP质量不佳,项目效率低下不说,还可能带来莫名的网络问题,是不是太闹心了?尤其是在面对海外专线IP时,到底怎么才能买到适合自己的呢?所以,挑IP绝对是个技…...
【SSH疑难排查】轻松解决新版OpenSSH连接旧服务器的“no matching...“系列算法协商失败问题
【SSH疑难排查】轻松解决新版OpenSSH连接旧服务器的"no matching..."系列算法协商失败问题 摘要: 近期,在使用较新版本的OpenSSH客户端连接老旧SSH服务器时,会遇到 "no matching key exchange method found", "n…...
MySQL JOIN 表过多的优化思路
当 MySQL 查询涉及大量表 JOIN 时,性能会显著下降。以下是优化思路和简易实现方法: 一、核心优化思路 减少 JOIN 数量 数据冗余:添加必要的冗余字段(如订单表直接存储用户名)合并表:将频繁关联的小表合并成…...