Posts shell
Post
Cancel

shell

shell

shell 是一种脚本命令

Shell 脚本(shell script),是一种为 shell 编写的脚本程序。’’

写一个shell 脚本

1
2
#!/bin/bash 
echo "Hello World !"

#! 是一个约定的标记,它告诉系统这个脚本需要什么解释器来执行,即使用哪一种 Shell。

echo 命令用于向窗口输出文本。

运行shell 脚本的方法

1 是脚本文件成为可执行文件

1
2
chmod +x ./test.sh  #使脚本具有执行权限
./test.sh  #执行脚本

2 作为解释器参数

这种运行方式是,直接运行解释器,其参数就是 shell 脚本的文件名,如:

1
/bin/sh test.sh

这种方法,脚本中不需要写#!/bin/bash 因为 /bin/sh 就是解释器,#!/bin/bash 就是同样的意思,告诉系统用/bin/sh 做运行解释器,只有在第一种方式,脚本文件第一行加入这个才有效。

shell变量定义

注意,变量名和等号之间不能有空格,这可能和你熟悉的所有编程语言都不一样。同时,变量名的命名须遵循如下规则:

  • 命名只能使用英文字母,数字和下划线,首个字符不能以数字开头。
  • 中间不能有空格,可以使用下划线(_)。
  • 不能使用标点符号。
  • 不能使用bash里的关键字(可用help命令查看保留关键字)。
1
2
3
4
#! /bin/bash
blog_name="wunanyu"
echo $blog_name #输出变量值
echo "${blog_name}simple" #输出变量值

只读变量

1
2
3
4
5
6
7
#! /bin/bash
blog_name="wunanyu"
echo $blog_name #输出变量值
echo "${blog_name}simple" #输出变量值
readonly bolg_name
blog_name="sj"
echo $blog_name

语句结构

1
2
3
4
5
6
7
8
9
if condition #条件
then 
	command #执行命令
elif otherCondition #条件
then
	command #执行命令
else
	command
fi

| 管道

在linux 中是非常好用的,配合 grep 就能过滤信息

编写shell脚本运行java程序

要求:能够启动和关闭java程序

流程设计

设置java程序名称

有 java运行的 pid

start -> 是否在运行? 没有就启动 有就输出已经在运行

stop -> 是否已经停止 没有就停止 有就输出程序已经停止

如果 java程序的jar包名为:Config-0.0.1-SNAPSHOT.jar

启动命令

nohup java -jar Config-0.0.1-SNAPSHOT.jar > config.log 2>&1 &

后台启动,并且将日志打印打 config.log

关闭命令

获取进程id,柔和关闭java程序 kill -9 强制关闭

pid=ps -ef | grep ${application} | grep -v grep |awk '{print $2}'

kill -15 pid

脚本

vim Config.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
echo $1 #输出命令

# 1.首先定义需要用到的变量
application=Config-0.0.1-SNAPSHOT.jar #1.1java程序应用名
#PID=`cat config-pid`
PID=`ps -ef | grep ${application} | grep -v grep |awk '{print $2}'` #获取1.2pid

# 2.判断输入命令 执行对应的动作
if [[ $1 == "start" ]]  #2.1启动脚本
then
        if [[ -z "$PID" ]] #如果pid 长度为0 表示程序没有启动
        then
                nohup java -jar Config-0.0.1-SNAPSHOT.jar > config.log 2>&1 &
        else # pid存在,说明程序已经启动,输出提示
                echo "${application} is already running"
        fi
elif [[ $1 == "stop" ]] #2.2关闭脚本
then
        if [[ -n "$PID" ]] #如果pid不为空值,说明程序在运行
        then
                kill -15 $PID # kill -9 强制关闭  -15柔和关闭
                #> config-pid # clean pid
        else
                echo "${application} is not running"
        fi
else # 其他命令 没有对应动作
        echo 'no this commond'

fi

chmod + x Config.sh #修改文件权限,成为可执行文件

This post is licensed under CC BY 4.0 by the author.

数据加密

fail2ban 防ssh暴力破解

Comments powered by Disqus.