shell脚本

一、前言

由于笔者最近从事的工作是自动化开发,所使用的开发开发语言是python,但其中也有shell脚本的开发,shell脚本主要是简单,可以让功能可以重复执行,

eg:运行功能前需要部署环境,这时就可以写到shell脚本中,方便后期重复运行;

二、运行环境

编辑的好的shell脚本,运行时需要linux环境,一般需要使用对应的终端,像(ubuntu fedora redhat centos UOS KYLIN)等等,这其实比较麻烦,学习时,

其实可以安装个有linux终端的软件就行,例如:git bash就是一个不错的选择

三、编辑shell脚本

1、windows下,就新建个.sh结尾的文件,用行编辑器文件打开就行(eg:notepad++)

2、linux下,直接就用vi编辑器打开就行;

四、脚本内容功能介绍:

1、获取执行脚本的路径、名称、参数个数、参数内容等;

2、打印调试信息;

3、函数

4、选择、循环

5、输入输出重定向

6、bash执行其它的shell脚本;

7、凡是可以放到终端中的命令都可以放到shell脚本中让执行;

8、sed -i 命令

一般就是修改配置参数或者路径等

下面写个demo

bash 复制代码
#!/bin/bash

dirname=$(dirname "$(realpath "$0")")  
echo $dirname

echo "The zero parameter  :"$0
echo "The first parameter :"$1
echo "The second parameter:"$2

prog="$(basename $0)"

prepare_environment(){
	echo -e "\033[1;34mPrepare environment...\033[1;37m"
	#echo -e "\033[1;31mnpu...\033[1;37m"
}

func(){
	echo "开始执行业务"
}

clean_environment(){
	echo -e "\033[1;34mClean environment...\033[1;37m"
}

help(){
	echo "Usage:$prog[OPTION]"
	echo
	echo "Options:"
	echo
	echo " -m,--mode[1p,8p]"
	echo " -t,--type[acc,perf]"
	echo " -h,--help Print this help."
	echo 
}


while [ $# -gt 0 ]; do  
    case "$1" in  
        -m|--mode)  
            shift  # 移除当前选项  
            if [ -z "$(echo $1 | grep '^-')" ]; then  # 检查下一个参数是否不以'-'开头  
                mode=$1  # 赋值给mode变量  
                shift  # 移除已处理的参数  
            else  
                echo "Error: --mode requires an argument." >&2  
                exit 1  
            fi  
            ;;  
        -t|--type)  
            shift  # 移除当前选项  
            if [ -z "$(echo $1 | grep '^-')" ]; then  # 检查下一个参数是否不以'-'开头  
                type=$1  # 赋值给precision变量  
                shift  # 移除已处理的参数  
            else  
                echo "Error: --type requires an argument." >&2  
                exit 1  
            fi  
            ;;
        -h|--help)  
			help>&2
            exit 2
			;;  	
        *)  
		echo "${0}:${1}:invalid option" >&2
		help>&2
		exit 2
		;;  
    esac  
done  
  
# 这里可以添加使用mode和precision变量的代码  
echo "Mode: $mode"  
echo "Type: $type"
prepare_environment
func
clean_environment

###################################
#sed -i
###################################
temp='/home/file'
echo $temp
sed -i "s|CKPT_LOAD_DIR=.*|CKPT_LOAD_DIR=\"$temp\"|g" ./demo.sh
sed -i "s|--seq-length.*|--seq-length 1024 |g" ./demo.sh

运行结果为:

相关推荐
长流小哥1 天前
Linux 深入浅出信号量:从线程到进程的同步与互斥实战指南
linux·c语言·开发语言·bash
難釋懷1 天前
bash的特性-常见的快捷键
开发语言·bash
HORSE RUNNING WILD2 天前
为什么我们需要if __name__ == __main__:
linux·python·bash·学习方法
CodeWithMe3 天前
【Linux C】简单bash设计
linux·c语言·bash
听到微笑4 天前
使用ZSH美化Windows系统Git Bash
windows·git·bash
搜搜秀5 天前
find指令中使用正则表达式
linux·运维·服务器·正则表达式·bash
seeyoutlb6 天前
bash脚本手动清空mysql表数据
mysql·adb·bash
vortex56 天前
探索 Shell 中的扩展通配符:从 Bash 到 Zsh
linux·运维·bash·shell·zsh
cosX+sinY8 天前
ubuntu 20.04 复现 LVI-SAM
linux·ubuntu·机器人·bash
时雨h8 天前
《Spring Boot+策略模式:企业级度假订单Excel导入系统的架构演进与技术实现》
开发语言·bash