diff --git a/README.md b/README.md index 7a163dc..6919623 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ > > 📖 [电子书](https://dunwu.github.io/linux-tutorial/) | [电子书(国内)](http://turnon.gitee.io/linux-tutorial/) -| :wrench: | :shell: | :memo: | 📚 | -| :-------------------: | :-------------------: | :---------------: | :-------------------: | -| [软件运维](#软件运维) | [运维和脚本](#运维和脚本) | [知识点](#知识点) | [学习资源](#学习资源) | +| 🛠 | 🐚 | 📝 | 📚 | +| :-------------------: | :-----------------------: | :-----------: | :-------------------: | +| [软件运维](#软件运维) | [Shell 脚本](#Shell-脚本) | [教程](#教程) | [学习资源](#学习资源) | ## 软件运维 @@ -37,21 +37,21 @@ - [Mongodb 运维](docs/linux/soft/mongodb-ops.md) - [Redis 运维](docs/linux/soft/redis-ops.md) -## 运维和脚本 +## Shell 脚本 -- [系统运维脚本集合](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/sys) -- [工具脚本集合](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/soft) -- [Vim 应用指南](docs/linux/ops/vim.md) -- [Zsh 应用指南](docs/linux/ops/zsh.md) -- [Shell 教程](docs/linux/ops/shell.md) -- [Python 教程](docs/linux/ops/python.md) -- [Systemd 入门教程](docs/linux/ops/systemd.md) +### Shell 脚本大全 -> 提供一键式运维、配置软件脚本 +**Shell 脚本大全** 精心收集、整理了 Linux 环境下的常见 Shell 脚本操作片段。 -## 知识点 +源码:[**Shell 脚本大全**](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/sys) -### Linux +### CentOS 常规操作运维脚本集合 + +本人作为一名 Java 后端,苦于经常在 CentOS 环境上开荒虚拟机。为提高效率,写了一套 Shell 脚本,提供如下功能:安装常用 lib 库、命令工具、设置 DNS、NTP、配置国内 yum 源、一键安装常用软件等。 + +源码:[**CentOS 常规操作运维脚本集合**](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/sys) + +## 教程 - [Linux 命令教程](docs/linux/cli/README.md) - [查看 Linux 命令帮助信息](docs/linux/cli/查看Linux命令帮助信息.md) @@ -63,23 +63,23 @@ - [Linux 网络管理](docs/linux/cli/Linux网络管理.md) - [Linux 硬件管理](docs/linux/cli/Linux硬件管理.md) - [Linux 软件管理](docs/linux/cli/Linux硬件管理.md) -- [Linux 运维](docs/linux/ops/README.md) - - [linux 典型运维应用](docs/linux/ops/linux典型运维应用.md) - - [samba 使用详解](docs/linux/ops/samba使用详解.md) - -### Docker - - [Docker 教程](docs/docker) - [Docker 应用指南](docs/docker/docker.md) - [Docker Cheat Sheet](docs/docker/docker-cheat-sheet.md) - -### Git - - [Git 教程](docs/git/README.md) - [Git 快速指南](docs/git/git-quickstart.md) - [Git 配置](docs/git/git-configuration.md) - [git-flow 工作流](docs/git/git-flow.md) - [Git 常见问题](docs/git/git-faq.md) +- 运维 + - [linux 典型运维应用](docs/linux/ops/linux典型运维应用.md) + - [samba 使用详解](docs/linux/ops/samba使用详解.md) + - [Systemd 教程](docs/linux/ops/systemd.md) +- 脚本 + - [Vim 应用指南](docs/linux/ops/vim.md) + - [Zsh 应用指南](docs/linux/ops/zsh.md) + - [Shell 教程](docs/linux/ops/shell.md) + - [Python 教程](docs/linux/ops/python.md) ## 学习资源 diff --git a/codes/linux/README.md b/codes/linux/README.md index acd0e77..1cac0be 100644 --- a/codes/linux/README.md +++ b/codes/linux/README.md @@ -1,4 +1,4 @@ -# Dunwu Shell 运维脚本 +# CentOS 常规操作运维脚本集合 > **本项目脚本代码用于在 [CentOS](https://www.centos.org/) 机器上安装常用命令工具或开发软件。** diff --git a/codes/linux/build/helper.sh b/codes/linux/build/helper.sh index 2466cd6..4b780a0 100644 --- a/codes/linux/build/helper.sh +++ b/codes/linux/build/helper.sh @@ -2,7 +2,7 @@ # 打印UI页头信息 function printHeadInfo() { - cat << EOF + cat << EOF *********************************************************************************** * 欢迎使用项目引导式发布脚本。 * 输入任意键进入脚本操作。 @@ -12,7 +12,7 @@ EOF # 打印UI页尾信息 function printFootInfo() { - cat << EOF + cat << EOF *********************************************************************************** @@ -25,18 +25,18 @@ EOF # 检查文件是否存在,不存在则退出脚本 function checkFileExist() { - if [ ! -f "$1" ] - then - echo "关键文件 $1 找不到,脚本执行结束" - exit 1 - fi + if [ ! -f "$1" ] + then + echo "关键文件 $1 找不到,脚本执行结束" + exit 1 + fi } # 检查文件夹是否存在,不存在则创建 function createFolderIfNotExist() { - if [ ! -d "$1" ]; then - mkdir -p "$1" - fi + if [ ! -d "$1" ]; then + mkdir -p "$1" + fi } # 记录发布的版本信息 @@ -45,18 +45,18 @@ function createFolderIfNotExist() { # 第三个参数为代码分支 # 第四个参数为运行环境 function saveVersionInfo() { - if [ "$1" == "" ] || [ "$2" == "" ] || [ "$3" == "" ] || [ "$4" == "" ]; then - echo "缺少参数,退出" - exit 1 - fi + if [ "$1" == "" ] || [ "$2" == "" ] || [ "$3" == "" ] || [ "$4" == "" ]; then + echo "缺少参数,退出" + exit 1 + fi - VERSION_LOG_FILE=$1/$2-version.log - rm -rf ${VERSION_LOG_FILE} - touch ${VERSION_LOG_FILE} - chmod 777 ${VERSION_LOG_FILE} + VERSION_LOG_FILE=$1/$2-version.log + rm -rf ${VERSION_LOG_FILE} + touch ${VERSION_LOG_FILE} + chmod 777 ${VERSION_LOG_FILE} - echo -e "\n=================== $2 ===================" >> ${VERSION_LOG_FILE} - echo "Branch is: $3" >> ${VERSION_LOG_FILE} - echo "Profile is: $4" >> ${VERSION_LOG_FILE} - echo "CommitID is : $(git log --pretty=oneline -1)" >> ${VERSION_LOG_FILE} + echo -e "\n=================== $2 ===================" >> ${VERSION_LOG_FILE} + echo "Branch is: $3" >> ${VERSION_LOG_FILE} + echo "Profile is: $4" >> ${VERSION_LOG_FILE} + echo "CommitID is : $(git log --pretty=oneline -1)" >> ${VERSION_LOG_FILE} } diff --git a/codes/linux/build/java-app-boot.sh b/codes/linux/build/java-app-boot.sh index 85db911..cbd8deb 100644 --- a/codes/linux/build/java-app-boot.sh +++ b/codes/linux/build/java-app-boot.sh @@ -7,76 +7,76 @@ # 检查脚本参数,如必要参数未传入,退出脚本。 function checkInput() { - if [ "${app}" == "" ] || [ "${oper}" == "" ] || [ "${javaArgs}" == "" ] || [ "${classpathArgs}" == "" ] || [ "${bootstrapClass}" == "" ]; then - echo "请输入脚本参数:app oper javaArgs classpathArgs bootstrapClass" - echo " app: 应用名。" - echo " oper: 运行环境(必填)。可选值:start|stop|restart" - echo " javaArgs: JVM 参数(必填)。" - echo " classpathArgs: classpath参数(必填)。" - echo " bootstrapClass: 启动类(必填)。" - exit 0 - fi + if [ "${app}" == "" ] || [ "${oper}" == "" ] || [ "${javaArgs}" == "" ] || [ "${classpathArgs}" == "" ] || [ "${bootstrapClass}" == "" ]; then + echo "请输入脚本参数:app oper javaArgs classpathArgs bootstrapClass" + echo " app: 应用名。" + echo " oper: 运行环境(必填)。可选值:start|stop|restart" + echo " javaArgs: JVM 参数(必填)。" + echo " classpathArgs: classpath参数(必填)。" + echo " bootstrapClass: 启动类(必填)。" + exit 0 + fi } # 检查文件夹是否存在,不存在则创建 function createFolderIfNotExist() { - if [ ! -d "$1" ]; then - mkdir -p "$1" - fi + if [ ! -d "$1" ]; then + mkdir -p "$1" + fi } # 检查服务是否已经启动 pids="" function checkStarted() { - pids=`ps -ef | grep java | grep ${app} | awk '{print $2}'` - if [ -n "${pids}" ]; then - return 0 - else - return 1 - fi + pids=`ps -ef | grep java | grep ${app} | awk '{print $2}'` + if [ -n "${pids}" ]; then + return 0 + else + return 1 + fi } function main() { - case "${oper}" in - start) - echo -n "starting server: " - # 检查服务是否已经启动 - if checkStarted; then - echo "ERROR: server already started!" - echo "PID: ${pids}" - exit 1 - fi + case "${oper}" in + start) + echo -n "starting server: " + # 检查服务是否已经启动 + if checkStarted; then + echo "ERROR: server already started!" + echo "PID: ${pids}" + exit 1 + fi - args="${javaArgs} -classpath ${classpathArgs} ${bootstrapClass}" - echo -e "statup params:\n ${args}" + args="${javaArgs} -classpath ${classpathArgs} ${bootstrapClass}" + echo -e "statup params:\n ${args}" - #启动服务 - touch ${LOG_DIR}/${app}-startup.log - nohup java ${args} > ${LOG_DIR}/${app}-startup.log 2>&1 & - # echo -e "执行参数:\n${args}" - echo -e "\nthe server is started..." - ;; - stop) - echo -n "stopping server: " - #dubbo提供优雅停机, 不能使用kill -9 - if checkStarted; then - kill ${pids} - echo -e "\nthe server is stopped..." - else - echo -e "\nno server to be stopped..." - fi - ;; - restart) - $0 ${app} stop "${javaArgs}" "${classpathArgs}" "${bootstrapClass}" - sleep 5 - $0 ${app} start "${javaArgs}" "${classpathArgs}" "${bootstrapClass}" - ;; - *) - echo "Invalid oper: ${oper}." - exit 1 - esac + #启动服务 + touch ${LOG_DIR}/${app}-startup.log + nohup java ${args} > ${LOG_DIR}/${app}-startup.log 2>&1 & + # echo -e "执行参数:\n${args}" + echo -e "\nthe server is started..." + ;; + stop) + echo -n "stopping server: " + #dubbo提供优雅停机, 不能使用kill -9 + if checkStarted; then + kill ${pids} + echo -e "\nthe server is stopped..." + else + echo -e "\nno server to be stopped..." + fi + ;; + restart) + $0 ${app} stop "${javaArgs}" "${classpathArgs}" "${bootstrapClass}" + sleep 5 + $0 ${app} start "${javaArgs}" "${classpathArgs}" "${bootstrapClass}" + ;; + *) + echo "Invalid oper: ${oper}." + exit 1 + esac - exit 0 + exit 0 } ######################################## MAIN ######################################## diff --git a/codes/linux/build/java-app-release.sh b/codes/linux/build/java-app-release.sh index 02b77c0..7f34ab4 100644 --- a/codes/linux/build/java-app-release.sh +++ b/codes/linux/build/java-app-release.sh @@ -7,41 +7,41 @@ # 检查脚本参数,如必要参数未传入,退出脚本。 checkInput() { - if [ "${branch}" == "" ] || [ "${profile}" == "" ]; then - echo "请输入脚本参数:branch profile" - echo " branch: git分支(必填)。如 feature/1.1.16, master" - echo " profile: 运行环境(必填)。可选值:development | test" - echo "例:./java-app-release.sh feature/1.1.16 test" - exit 0 - fi + if [ "${branch}" == "" ] || [ "${profile}" == "" ]; then + echo "请输入脚本参数:branch profile" + echo " branch: git分支(必填)。如 feature/1.1.16, master" + echo " profile: 运行环境(必填)。可选值:development | test" + echo "例:./java-app-release.sh feature/1.1.16 test" + exit 0 + fi } # 检查文件是否存在,不存在则退出脚本 checkFileExist() { - if [ ! -f "$1" ] - then - echo "关键文件 $1 找不到,脚本执行结束" - exit 0 - fi + if [ ! -f "$1" ] + then + echo "关键文件 $1 找不到,脚本执行结束" + exit 0 + fi } # 检查文件夹是否存在,不存在则创建 createFolderIfNotExist() { - if [ ! -d "$1" ]; then - mkdir -p "$1" - fi + if [ ! -d "$1" ]; then + mkdir -p "$1" + fi } # 记录发布的版本信息 saveVersionInfo() { - rm -rf ${VERSION_LOG_FILE} - touch ${VERSION_LOG_FILE} - chmod 777 ${VERSION_LOG_FILE} + rm -rf ${VERSION_LOG_FILE} + touch ${VERSION_LOG_FILE} + chmod 777 ${VERSION_LOG_FILE} - echo -e "\n=================== Version Info ===================" >> ${VERSION_LOG_FILE} - echo "Branch is: ${branch}" >> ${VERSION_LOG_FILE} - echo "Profile is: ${profile}" >> ${VERSION_LOG_FILE} - echo "CommitID is : $(git log --pretty=oneline -1)" >> ${VERSION_LOG_FILE} + echo -e "\n=================== Version Info ===================" >> ${VERSION_LOG_FILE} + echo "Branch is: ${branch}" >> ${VERSION_LOG_FILE} + echo "Profile is: ${profile}" >> ${VERSION_LOG_FILE} + echo "CommitID is : $(git log --pretty=oneline -1)" >> ${VERSION_LOG_FILE} } ######################################## MAIN ######################################## @@ -74,10 +74,10 @@ echo ">>>>>>>>>>>>>> 2. 更新代码" ${UPDATE_CODE_SCRIPT_FILE} ${APP_NAME} ${branch} ${SOURCE_DIR} execode=$? if [ "${execode}" == "0" ]; then - echo "更新代码成功" + echo "更新代码成功" else - echo "更新代码失败" - exit 1 + echo "更新代码失败" + exit 1 fi echo ">>>>>>>>>>>>>> 3. 替换配置" @@ -88,12 +88,12 @@ cd ${SOURCE_DIR}/ck-lion mvn clean package -e -Dmaven.test.skip=true | tee ${MAVEN_LOG_FILE} eexecode=$? if [ "${execode}" == "0" ]; then - echo "构建编译成功" - echo "编译详情见:${MAVEN_LOG_FILE}" + echo "构建编译成功" + echo "编译详情见:${MAVEN_LOG_FILE}" else - echo "构建编译失败" - echo "编译详情见:${MAVEN_LOG_FILE}" - exit 1 + echo "构建编译失败" + echo "编译详情见:${MAVEN_LOG_FILE}" + exit 1 fi echo ">>>>>>>>>>>>>> 5. 启动应用" @@ -102,10 +102,10 @@ echo 3 > /proc/sys/vm/drop_caches ${SCRIPT_DIR}/java-app-run.sh ${profile} start execode=$? if [ "${execode}" == "0" ]; then - echo "启动应用成功" + echo "启动应用成功" else - echo "启动应用失败" - exit 1 + echo "启动应用失败" + exit 1 fi echo ">>>>>>>>>>>>>> 6. 记录发布的版本信息" diff --git a/codes/linux/build/java-app-run.sh b/codes/linux/build/java-app-run.sh index db81b24..69006de 100644 --- a/codes/linux/build/java-app-run.sh +++ b/codes/linux/build/java-app-run.sh @@ -7,51 +7,51 @@ # 检查脚本参数,如必要参数未传入,退出脚本。 function checkInput() { - if [ "${profile}" == "" ] || [ "${oper}" == "" ]; then - echo "请输入脚本参数:profile oper [debug]" - echo " profile: 运行环境(必填)。可选值:development|test" - echo " oper: 运行环境(必填)。可选值:start|stop|restart" - echo " debug: debug启动开关。默认不填为不启动。" - exit 0 - fi + if [ "${profile}" == "" ] || [ "${oper}" == "" ]; then + echo "请输入脚本参数:profile oper [debug]" + echo " profile: 运行环境(必填)。可选值:development|test" + echo " oper: 运行环境(必填)。可选值:start|stop|restart" + echo " debug: debug启动开关。默认不填为不启动。" + exit 0 + fi } #检查文件是否存在,不存在则退出脚本 function checkFileExist() { - if [ ! -f "$1" ] - then - echo "关键文件 $1 找不到,脚本执行结束" - exit 0 - fi + if [ ! -f "$1" ] + then + echo "关键文件 $1 找不到,脚本执行结束" + exit 0 + fi } # 封装启动参数,调用启动脚本 function main() { - APP_NAME=ck-lion + APP_NAME=ck-lion - # JVM 参数 - JAVA_OPTS=" -Djava.awt.headless=true -Dfile.encoding=UTF8 -Djava.net.preferIPv4Stack=true -Ddubbo.shutdown.hook=true -Dspring.profiles.active=${profile} -Djava.security.egd=file:/dev/./urandom -Xms1024m -Xmx1024m -Xss2m " - JAVA_DEBUG_OPTS="" - if [ "$2" == "debug" ]; then - JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=2236,server=y,suspend=n " - shift - fi - javaArgs=" ${JAVA_OPTS} ${JAVA_DEBUG_OPTS} " + # JVM 参数 + JAVA_OPTS=" -Djava.awt.headless=true -Dfile.encoding=UTF8 -Djava.net.preferIPv4Stack=true -Ddubbo.shutdown.hook=true -Dspring.profiles.active=${profile} -Djava.security.egd=file:/dev/./urandom -Xms1024m -Xmx1024m -Xss2m " + JAVA_DEBUG_OPTS="" + if [ "$2" == "debug" ]; then + JAVA_DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=2236,server=y,suspend=n " + shift + fi + javaArgs=" ${JAVA_OPTS} ${JAVA_DEBUG_OPTS} " - # classpath 参数 - classpathArgs="${SERVER_ROOT}/WEB-INF/classes:${SERVER_ROOT}/WEB-INF/lib/*" + # classpath 参数 + classpathArgs="${SERVER_ROOT}/WEB-INF/classes:${SERVER_ROOT}/WEB-INF/lib/*" - # 启动类 - bootstrapClass="com.alibaba.dubbo.container.Main" + # 启动类 + bootstrapClass="com.alibaba.dubbo.container.Main" - ${SCRIPT_DIR}/java-app-boot.sh ${APP_NAME} ${oper} "${javaArgs}" "${classpathArgs}" "${bootstrapClass}" - execode=$? - if [ "${execode}" == "0" ]; then - echo "执行操作成功" - else - echo "执行操作失败" - exit 1 - fi + ${SCRIPT_DIR}/java-app-boot.sh ${APP_NAME} ${oper} "${javaArgs}" "${classpathArgs}" "${bootstrapClass}" + execode=$? + if [ "${execode}" == "0" ]; then + echo "执行操作成功" + else + echo "执行操作失败" + exit 1 + fi } ######################################## MAIN ######################################## diff --git a/codes/linux/build/js-app-release.sh b/codes/linux/build/js-app-release.sh index 617d9ae..aa08a21 100644 --- a/codes/linux/build/js-app-release.sh +++ b/codes/linux/build/js-app-release.sh @@ -5,50 +5,50 @@ # 检查脚本参数,如必要参数未传入,退出脚本。 function checkInput() { - if [ "${branch}" == "" ]; then - echo "请输入脚本参数:branch" - echo " branch: git分支。如 feature/1.1.16, master" - exit 1 - fi + if [ "${branch}" == "" ]; then + echo "请输入脚本参数:branch" + echo " branch: git分支。如 feature/1.1.16, master" + exit 1 + fi } # 脚本主方法 function main() { - echo ">>>>>>>>>>>>>> 1. 更新代码" - ${SCRIPT_DIR}/update-code.sh ${APP} ${branch} ${SOURCE_DIR} - execode=$? - if [ "${execode}" == "0" ]; then - echo "更新代码成功" - else - echo "更新代码失败" - exit 1 - fi + echo ">>>>>>>>>>>>>> 1. 更新代码" + ${SCRIPT_DIR}/update-code.sh ${APP} ${branch} ${SOURCE_DIR} + execode=$? + if [ "${execode}" == "0" ]; then + echo "更新代码成功" + else + echo "更新代码失败" + exit 1 + fi - echo ">>>>>>>>>>>>>> 2. 替换配置" - # 有的应用此处可能需要替换配置 + echo ">>>>>>>>>>>>>> 2. 替换配置" + # 有的应用此处可能需要替换配置 - echo ">>>>>>>>>>>>>> 3. 构建编译" - cd ${SOURCE_DIR}/${APP} - source "${HOME}/.nvm/nvm.sh" - nvm use 8.9 - npm install - if [ "${profile}" == "develop" ] || [ "${profile}" == "test" ]; then - npm start - elif [ "${profile}" == "preview" ] || [ "${profile}" == "product" ]; then - npm run build - fi - execode=$? - if [ "${execode}" == "0" ]; then - echo "构建编译成功" - else - echo "构建编译失败" - exit 1 - fi + echo ">>>>>>>>>>>>>> 3. 构建编译" + cd ${SOURCE_DIR}/${APP} + source "${HOME}/.nvm/nvm.sh" + nvm use 8.9 + npm install + if [ "${profile}" == "develop" ] || [ "${profile}" == "test" ]; then + npm start + elif [ "${profile}" == "preview" ] || [ "${profile}" == "product" ]; then + npm run build + fi + execode=$? + if [ "${execode}" == "0" ]; then + echo "构建编译成功" + else + echo "构建编译失败" + exit 1 + fi - echo ">>>>>>>>>>>>>> 4. 记录发布的版本信息" - saveVersionInfo ${LOG_DIR} ${APP} ${branch} ${profile} + echo ">>>>>>>>>>>>>> 4. 记录发布的版本信息" + saveVersionInfo ${LOG_DIR} ${APP} ${branch} ${profile} - echo ">>>>>>>>>>>>>> 发布应用结束" + echo ">>>>>>>>>>>>>> 发布应用结束" } ######################################## MAIN ######################################## diff --git a/codes/linux/build/main.sh b/codes/linux/build/main.sh index 26d92fe..7e8f2ab 100644 --- a/codes/linux/build/main.sh +++ b/codes/linux/build/main.sh @@ -7,7 +7,7 @@ # 选择应用 function chooseAppName() { - cat << EOF + cat << EOF 请选择应用名(数字或关键字均可)。 可选值如下: [0] all (所有应用) @@ -15,28 +15,28 @@ function chooseAppName() { [2] APP2 EOF - while read app - do - case ${app} in - 0) - app=all - break ;; - 1) - app=js-app - break ;; - 2) - app=APP2 - break ;; - all | js-app | APP2) - break ;; - *) echo "无法识别 ${app}" ;; - esac - done + while read app + do + case ${app} in + 0) + app=all + break ;; + 1) + app=js-app + break ;; + 2) + app=APP2 + break ;; + all | js-app | APP2) + break ;; + *) echo "无法识别 ${app}" ;; + esac + done } # 选择操作 function chooseOper() { - cat << EOF + cat << EOF 请选择想要执行的操作(数字或关键字均可)。 可选值如下: [1] start @@ -44,44 +44,44 @@ function chooseOper() { [3] stop EOF - while read oper - do - case ${oper} in - 1) - oper=start - break ;; - 2) - oper=restart - break ;; - 3) - oper=stop - break ;; - start | restart | stop) - break ;; - *) echo "无法识别 ${oper}" ;; - esac - done + while read oper + do + case ${oper} in + 1) + oper=start + break ;; + 2) + oper=restart + break ;; + 3) + oper=stop + break ;; + start | restart | stop) + break ;; + *) echo "无法识别 ${oper}" ;; + esac + done } # 选择代码分支 function chooseBranch() { - cat << EOF + cat << EOF 请输入 git 分支。 如:develop、master、feature/xxx EOF - read branch - if [[ "${branch}" =~ ^ ( feature/ ) ( [^ \f\n\r\t\v]+ ) ]] || [ "${branch}" == "develop" ] || [ "${branch}" == "master" ]; then - echo "输入了 ${branch}" - else - echo "无法识别 ${branch}" - chooseBranch - fi + read branch + if [[ "${branch}" =~ ^ ( feature/ ) ( [^ \f\n\r\t\v]+ ) ]] || [ "${branch}" == "develop" ] || [ "${branch}" == "master" ]; then + echo "输入了 ${branch}" + else + echo "无法识别 ${branch}" + chooseBranch + fi } # 选择运行环境 function chooseProfile() { - cat << EOF + cat << EOF 请选择运行环境(数字或关键字均可)。 可选值: [1] develop (开发环境) @@ -90,32 +90,32 @@ function chooseProfile() { [4] product (生产环境) EOF - while read profile - do - case ${profile} in - 1) - profile=develop - break ;; - 2) - profile=test - break ;; - 3) - profile=preview - break ;; - 4) - profile=product - break ;; - develop | test | preview | product) - break ;; - *) echo "无法识别 ${profile}" ;; - esac - done + while read profile + do + case ${profile} in + 1) + profile=develop + break ;; + 2) + profile=test + break ;; + 3) + profile=preview + break ;; + 4) + profile=product + break ;; + develop | test | preview | product) + break ;; + *) echo "无法识别 ${profile}" ;; + esac + done } # 确认选择 function confirmChoice() { - cat << EOF + cat << EOF =================================================== 请确认您的选择:Y/N app: ${app} @@ -125,66 +125,66 @@ function confirmChoice() { =================================================== EOF - while read confirm - do - case ${confirm} in - y | Y) - echo -e "\n\n>>>>>>>>>>>>>> 开始发布应用" - break ;; - n | N) - echo -e "重新输入发布参数\n" - inputParams ;; - *) - echo "无法识别 ${confirm}" ;; - esac - done + while read confirm + do + case ${confirm} in + y | Y) + echo -e "\n\n>>>>>>>>>>>>>> 开始发布应用" + break ;; + n | N) + echo -e "重新输入发布参数\n" + inputParams ;; + *) + echo "无法识别 ${confirm}" ;; + esac + done } # 引导式发布应用 function releaseApp() { - # 输入执行参数 - app="" - branch="" - profile="" - chooseAppName - chooseOper - if [ "${oper}" == "stop" ]; then - confirmChoice - if [ "${app}" == "all" ]; then - ${SCRIPT_DIR}/${app}-run.sh stop ${profile} - else - ${SCRIPT_DIR}/${app}-run.sh stop ${profile} - fi - else - chooseBranch - chooseProfile - confirmChoice - if [ "${app}" == "all" ]; then - ${SCRIPT_DIR}/js-app-release.sh ${branch} ${profile} - else - ${SCRIPT_DIR}/${app}-release.sh ${branch} ${profile} - fi - fi + # 输入执行参数 + app="" + branch="" + profile="" + chooseAppName + chooseOper + if [ "${oper}" == "stop" ]; then + confirmChoice + if [ "${app}" == "all" ]; then + ${SCRIPT_DIR}/${app}-run.sh stop ${profile} + else + ${SCRIPT_DIR}/${app}-run.sh stop ${profile} + fi + else + chooseBranch + chooseProfile + confirmChoice + if [ "${app}" == "all" ]; then + ${SCRIPT_DIR}/js-app-release.sh ${branch} ${profile} + else + ${SCRIPT_DIR}/${app}-release.sh ${branch} ${profile} + fi + fi } # 脚本主方法 function main() { - printHeadInfo - while read sign - do - case ${sign} in - exit) - echo "主动退出脚本" - exit 0 ;; - *) - releaseApp ;; - esac + printHeadInfo + while read sign + do + case ${sign} in + exit) + echo "主动退出脚本" + exit 0 ;; + *) + releaseApp ;; + esac - # 装载函数库 - printFootInfo - done + # 装载函数库 + printFootInfo + done } ######################################## MAIN ######################################## diff --git a/codes/linux/build/spring-boot-run.sh b/codes/linux/build/spring-boot-run.sh index d41a048..2d644c8 100644 --- a/codes/linux/build/spring-boot-run.sh +++ b/codes/linux/build/spring-boot-run.sh @@ -38,7 +38,7 @@ packageJavaOpts() { JAVA_OPTS="${JAVA_OPTS} -XX:HeapDumpPath=${LOG_PATH}/${APP_NAME}.heapdump.hprof" # JMX OPTS - IP=`ip addr|grep "inet "|grep -v 127.0.0.1|awk '{print $2}'|cut -d/ -f1` + IP=`ip addr | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1` JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote=true" JAVA_OPTS="${JAVA_OPTS} -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false" JAVA_OPTS="${JAVA_OPTS} -Djava.rmi.server.hostname=${IP} -Dcom.sun.management.jmxremote.port=18889" @@ -55,30 +55,30 @@ packageJavaOpts() { # 检查服务是否已经启动 pid="" checkStarted() { - pid=`ps -ef | grep java | grep ${APP_NAME} | awk '{print $2}'` - if [[ -n "${pid}" ]]; then - return 0 - else - return 1 - fi + pid=`ps -ef | grep java | grep ${APP_NAME} | awk '{print $2}'` + if [[ -n "${pid}" ]]; then + return 0 + else + return 1 + fi } main() { case "${oper}" in - start ) - startServer + start) + startServer ;; - stop ) - stopServer + stop) + stopServer ;; - restart ) - stopServer - sleep 5 - startServer + restart) + stopServer + sleep 5 + startServer ;; - * ) - echo "Invalid oper: ${oper}." - exit 1 + *) + echo "Invalid oper: ${oper}." + exit 1 esac exit 0 @@ -86,7 +86,7 @@ main() { stopServer() { echo -n "stopping server: " - if checkStarted ;then + if checkStarted; then kill -9 ${pid} printf "${GREEN}\n${APP_NAME} is stopped.${RESET}\n" else @@ -96,7 +96,7 @@ stopServer() { startServer() { printf "${BLUE}starting ${APP_NAME}...${RESET}\n" - if checkStarted ;then + if checkStarted; then printf "${YELLOW}[WARN] ${APP_NAME} already started!${RESET}\n" printf "PID: ${pid}\n" exit 1 @@ -121,7 +121,7 @@ LOG_PATH=${ROOT_DIR}/../logs mkdir -p ${LOG_PATH} declare -a serial -serial=(start stop restart) +serial=( start stop restart ) echo -n "请选择操作(可选值:start|stop|restart):" read oper if ! echo "${serial[@]}" | grep -q ${oper}; then @@ -131,7 +131,7 @@ fi if [[ ${oper} == "start" ]] || [[ "${oper}" == "restart" ]]; then declare -a serial2 - serial2=(prod dev test) + serial2=( prod dev test ) echo -n "选择 profile(可选值:prod|dev|test):" read profile if ! echo "${serial2[@]}" | grep -q ${profile}; then @@ -140,7 +140,7 @@ if [[ ${oper} == "start" ]] || [[ "${oper}" == "restart" ]]; then fi declare -a serial3 - serial3=(on off) + serial3=( on off ) echo -n "是否启动 debug 模式(可选值:on|off):" read debug if ! echo "${serial3[@]}" | grep -q ${debug}; then diff --git a/codes/linux/build/update-code.sh b/codes/linux/build/update-code.sh index cadaa7e..c3b14f6 100644 --- a/codes/linux/build/update-code.sh +++ b/codes/linux/build/update-code.sh @@ -8,78 +8,78 @@ # 检查脚本参数,如必要参数未传入,退出脚本。 checkInput() { - if [ "${repository}" == "" ] || [ "${branch}" == "" ]; then - echo "请输入脚本参数:repository branch [source] [target]" - echo " repository: git 仓储(必填)。" - echo " branch: git 分支(必填)。如 master/develop" - echo " source: 代码存放目录。默认为/home/zp/source。" - echo " target: 代码存放目录。默认为脚本所在目录。" - exit 1 - fi + if [ "${repository}" == "" ] || [ "${branch}" == "" ]; then + echo "请输入脚本参数:repository branch [source] [target]" + echo " repository: git 仓储(必填)。" + echo " branch: git 分支(必填)。如 master/develop" + echo " source: 代码存放目录。默认为/home/zp/source。" + echo " target: 代码存放目录。默认为脚本所在目录。" + exit 1 + fi } # 检查文件夹是否存在,不存在则创建 function createFolderIfNotExist() { - if [ ! -d "$1" ]; then - mkdir -p "$1" - fi + if [ ! -d "$1" ]; then + mkdir -p "$1" + fi } # 判断 git 版本库是否存在。根据实际结果修改 ${gitok} 值。 gitok=false function isGitExist() { - cd ${SOURCE_DIR} - if [ -d "${SOURCE_DIR}/${repository}/${target}" ]; then - cd ${SOURCE_DIR}/${repository}/${target} - #(1)删除git状态零时文件 - if [ -f "gitstatus.tmp" ]; then - rm -rf gitstatus.tmp - fi + cd ${SOURCE_DIR} + if [ -d "${SOURCE_DIR}/${repository}/${target}" ]; then + cd ${SOURCE_DIR}/${repository}/${target} + #(1)删除git状态零时文件 + if [ -f "gitstatus.tmp" ]; then + rm -rf gitstatus.tmp + fi - #(2) 判断是否存在.git目录 - if [ -d "./.git" ]; then - #(3) 判断git是否可用 - git status &> gitstatus.tmp - grep -iwq 'not a git repository' gitstatus.tmp && gitok=false || gitok=true - fi + #(2) 判断是否存在.git目录 + if [ -d "./.git" ]; then + #(3) 判断git是否可用 + git status &> gitstatus.tmp + grep -iwq 'not a git repository' gitstatus.tmp && gitok=false || gitok=true + fi - #返回到主目录 - cd ${SOURCE_DIR} - fi + #返回到主目录 + cd ${SOURCE_DIR} + fi } # 如果 git 版本库存在(根据 ${gitok} 值),执行 fetch 操作;反之,执行 clone 操作。 function doFetchOrClone() { - if ${gitok}; then - cd ${SOURCE_DIR}/${repository}/${target} - git reset --hard - git clean -ffdx - git fetch - echo "git fetch ${repository} remote repository 到本地成功" - else - #删除所有内容,便于重新进行git clone - rm -rf ${repository} - git clone --no-checkout git@github.com:${GITHUB_ACCOUNT}/${repository}.git ${SOURCE_DIR}/${repository}/${target} - echo "git clone ${repository} remote repository 到本地成功" - cd ${SOURCE_DIR}/${repository}/${target} - fi + if ${gitok}; then + cd ${SOURCE_DIR}/${repository}/${target} + git reset --hard + git clean -ffdx + git fetch + echo "git fetch ${repository} remote repository 到本地成功" + else + #删除所有内容,便于重新进行git clone + rm -rf ${repository} + git clone --no-checkout git@github.com:${GITHUB_ACCOUNT}/${repository}.git ${SOURCE_DIR}/${repository}/${target} + echo "git clone ${repository} remote repository 到本地成功" + cd ${SOURCE_DIR}/${repository}/${target} + fi } # 切换到 ${branch} 分支 function doCheckout() { - echo "检出 ${repository} ${branch} 分支代码" - isRemoteBranch=false - gitRemoteBranch=`git branch -r` - echo -e "$gitRemoteBranch" | grep -iwq ${branch} && isRemoteBranch=true || isRemoteBranch=false - if ${isRemoteBranch}; then - echo "找到 ${branch} 分支。" - git checkout -f 'origin/'${branch} - else - echo "未找到 ${branch} 分支!" - exit 2 - fi - echo "更新子模块代码" - git submodule update --init --recursive --force + echo "检出 ${repository} ${branch} 分支代码" + isRemoteBranch=false + gitRemoteBranch=`git branch -r` + echo -e "$gitRemoteBranch" | grep -iwq ${branch} && isRemoteBranch=true || isRemoteBranch=false + if ${isRemoteBranch}; then + echo "找到 ${branch} 分支。" + git checkout -f 'origin/'${branch} + else + echo "未找到 ${branch} 分支!" + exit 2 + fi + echo "更新子模块代码" + git submodule update --init --recursive --force } ######################################## MAIN ######################################## @@ -96,7 +96,7 @@ checkInput GITHUB_ACCOUNT=dunwu SOURCE_DIR=/home/xyz/source if [ "${source}" != "" ]; then - SOURCE_DIR=${source} + SOURCE_DIR=${source} fi createFolderIfNotExist ${SOURCE_DIR} diff --git a/codes/linux/download.sh b/codes/linux/download.sh index 96ae881..0438d15 100644 --- a/codes/linux/download.sh +++ b/codes/linux/download.sh @@ -29,7 +29,7 @@ root=/home/scripts/linux-tutorial printf "\n${GREEN}>>>>>>>> Download linux-tutorial to ${root} begin.${RESET}\n" command -v yum > /dev/null 2>&1 || { printf "\n${RED}Not detected yum.${RESET}"; - exit 1; + exit 1; } command -v git > /dev/null 2>&1 || { @@ -38,11 +38,11 @@ command -v git > /dev/null 2>&1 || { } if [[ -d ${root} ]]; then - cd ${root} - git pull + cd ${root} + git pull else - mkdir -p ${root} - git clone https://gitee.com/turnon/linux-tutorial.git ${root} + mkdir -p ${root} + git clone https://gitee.com/turnon/linux-tutorial.git ${root} fi chmod +x -R ${root} printf "\n${GREEN}<<<<<<<< Download linux-tutorial to ${root} end.${RESET}\n" diff --git a/codes/linux/dunwu-ops.sh b/codes/linux/dunwu-ops.sh index 100bd72..14a1b2b 100644 --- a/codes/linux/dunwu-ops.sh +++ b/codes/linux/dunwu-ops.sh @@ -14,67 +14,67 @@ RESET="$(tput sgr0)" # 打印头部信息 printHeadInfo() { -printf "${BLUE}\n" -cat << EOF + printf "${BLUE}\n" + cat << EOF ################################################################################### # 欢迎使用 Dunwu Shell 运维脚本 # 适用于 Linux CentOS 环境 # @author: Zhang Peng ################################################################################### EOF -printf "${RESET}\n" + printf "${RESET}\n" } # 打印尾部信息 printFootInfo() { -printf "${BLUE}\n" -cat << EOF + printf "${BLUE}\n" + cat << EOF ################################################################################### # 脚本执行结束,感谢使用! ################################################################################### EOF -printf "${RESET}\n" + printf "${RESET}\n" } # 检查操作系统环境 checkOsVersion() { - if (($1 == 1)); then - platform=`uname -i` - if [[ ${platform} != "x86_64" ]]; then - printf "\n${RED}脚本仅支持 64 位操作系统!${RESET}\n" - exit 1 - fi + if (($1 == 1)); then + platform=`uname -i` + if [[ ${platform} != "x86_64" ]]; then + printf "\n${RED}脚本仅支持 64 位操作系统!${RESET}\n" + exit 1 + fi - version=`cat /etc/redhat-release | awk '{print substr($4,1,1)}'` - if [[ ${version} != 7 ]]; then - printf "\n${RED}脚本仅支持 CentOS 7!${RESET}\n" - exit 1 - fi - fi + version=`cat /etc/redhat-release | awk '{print substr($4,1,1)}'` + if [[ ${version} != 7 ]]; then + printf "\n${RED}脚本仅支持 CentOS 7!${RESET}\n" + exit 1 + fi + fi } menus=( "配置系统" "安装软件" "退出" ) selectAndExecTask() { printHeadInfo - PS3="请输入命令编号:" - select item in "${menus[@]}" - do - case ${item} in - "配置系统") - ./dunwu-sys.sh - selectAndExecTask ;; - "安装软件") - ./dunwu-soft.sh - selectAndExecTask ;; - "退出") - printFootInfo - exit 0 ;; - *) - printf "\n${RED}输入项不支持!${RESET}\n" - selectAndExecTask ;; - esac - break - done + PS3="请输入命令编号:" + select item in "${menus[@]}" + do + case ${item} in + "配置系统") + ./dunwu-sys.sh + selectAndExecTask ;; + "安装软件") + ./dunwu-soft.sh + selectAndExecTask ;; + "退出") + printFootInfo + exit 0 ;; + *) + printf "\n${RED}输入项不支持!${RESET}\n" + selectAndExecTask ;; + esac + break + done } diff --git a/codes/linux/dunwu-soft.sh b/codes/linux/dunwu-soft.sh index deb166e..7757311 100644 --- a/codes/linux/dunwu-soft.sh +++ b/codes/linux/dunwu-soft.sh @@ -41,26 +41,27 @@ printMenu() { # exec shell to install soft main() { printMenu - read -t 30 index - if [[ -n ${index} ]]; then - no=`expr ${index} - 1` - len=${#menus[*]} - if [[ ${index} -gt ${len} ]]; then - printf "${RED}输入项不支持!\n${RESET}" - exit -1 - fi - key=${menus[$no]} - if [[ ${key} == 'exit' ]]; then - printf "${GREEN}退出 Dunwu 软件安装脚本。\n${RESET}" - exit 0 - fi - sh soft/${key}-install.sh - printf "\n" - main - else - printf "${RED}输入项不支持!\n${RESET}" - exit -1 - fi + read -t 30 index + if [[ -n ${index} ]]; then + no=`expr ${index} - 1` + len=${#menus[*]} + if [[ ${index} -gt ${len} ]]; then + printf "${RED}输入项不支持!\n${RESET}" + exit -1 + fi + key=${menus[$no]} + if [[ ${key} == 'exit' ]]; then + printf "${GREEN}退出 Dunwu 软件安装脚本。\n${RESET}" + exit 0 + fi + sh soft/${key}-install.sh + printf "\n" + main + else + printf "${RED}输入项不支持!\n${RESET}" + exit -1 + fi } +######################################## MAIN ######################################## main diff --git a/codes/linux/dunwu-sys.sh b/codes/linux/dunwu-sys.sh index c40725d..bf2d3fb 100644 --- a/codes/linux/dunwu-sys.sh +++ b/codes/linux/dunwu-sys.sh @@ -24,38 +24,38 @@ printf "${RESET}\n" menus=( "替换yum镜像" "安装基本的命令工具" "安装常用libs" "系统配置" "全部执行" "退出" ) main() { - PS3="请输入命令编号:" - select item in "${menus[@]}" - do - case ${item} in - "替换yum镜像") - sh ${root}/sys/change-yum-repo.sh - main ;; - "安装基本的命令工具") - sh ${root}/sys/install-tools.sh - main ;; - "安装常用libs") - sh ${root}/sys/install-libs.sh - main ;; - "系统配置") - sh ${root}/sys/sys-settings.sh ${root}/sys - main ;; - "全部执行") - sh ${root}/sys/change-yum-repo.sh - sh ${root}/sys/install-tools.sh - sh ${root}/sys/install-libs.sh - sh ${root}/sys/sys-settings.sh ${root}/sys - printf "${GREEN}执行完毕,退出。${RESET}\n" ;; - "退出") - exit 0 ;; - *) - printf "${RED}输入项不支持!${RESET}\n" - main ;; - esac - break - done + PS3="请输入命令编号:" + select item in "${menus[@]}" + do + case ${item} in + "替换yum镜像") + sh ${path}/sys/change-yum-repo.sh + main ;; + "安装基本的命令工具") + sh ${path}/sys/install-tools.sh + main ;; + "安装常用libs") + sh ${path}/sys/install-libs.sh + main ;; + "系统配置") + sh ${path}/sys/sys-settings.sh ${path}/sys + main ;; + "全部执行") + sh ${path}/sys/change-yum-repo.sh + sh ${path}/sys/install-tools.sh + sh ${path}/sys/install-libs.sh + sh ${path}/sys/sys-settings.sh ${path}/sys + printf "${GREEN}执行完毕,退出。${RESET}\n" ;; + "退出") + exit 0 ;; + *) + printf "${RED}输入项不支持!${RESET}\n" + main ;; + esac + break + done } ######################################## MAIN ######################################## -root=$(pwd) +path=$(pwd) main diff --git a/codes/linux/soft/arthas-install.sh b/codes/linux/soft/arthas-install.sh index 3266f88..0a08892 100644 --- a/codes/linux/soft/arthas-install.sh +++ b/codes/linux/soft/arthas-install.sh @@ -25,7 +25,7 @@ printf "${BLUE}>>>>>>>> begin.\n${RESET}" root=/opt/arthas if [[ -n $1 ]]; then - root=$1 + root=$1 fi mkdir -p ${root} diff --git a/codes/linux/soft/config/nginx/nginx.conf b/codes/linux/soft/config/nginx/nginx.conf index 5e4d737..00a389b 100644 --- a/codes/linux/soft/config/nginx/nginx.conf +++ b/codes/linux/soft/config/nginx/nginx.conf @@ -1,36 +1,37 @@ -worker_processes 1; +worker_processes 1; -#error_log logs/error.log; -#error_log logs/error.log notice; -#error_log logs/error.log info; -pid /usr/local/nginx/logs/nginx.pid; +error_log logs/error.log; +#error_log logs/error.log notice; +#error_log logs/error.log info; +pid /usr/local/nginx/logs/nginx.pid; events { - worker_connections 1024; + worker_connections 1024; } http { - default_type application/octet-stream; - log_format main '$remote_addr - $remote_user [$time_local] "$request" ' - '$status $body_bytes_sent "$http_referer" ' - '"$http_user_agent" "$http_x_forwarded_for"'; - #access_log logs/nginx-http-access.log; - sendfile on; - rewrite_log on; - keepalive_timeout 65; + include mime.types; + include conf.d/*.conf; - client_max_body_size 20m; - client_body_buffer_size 128k; + default_type application/octet-stream; - #common header set - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + #access_log logs/nginx-http-access.log; - include mime.types; - include conf/*.conf; + sendfile on; + keepalive_timeout 65; + + client_max_body_size 20m; + client_body_buffer_size 128k; + + #common header set + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; } diff --git a/codes/linux/soft/config/redis/6381/redis.conf b/codes/linux/soft/config/redis/6381/redis.conf deleted file mode 100644 index f0315be..0000000 --- a/codes/linux/soft/config/redis/6381/redis.conf +++ /dev/null @@ -1,12 +0,0 @@ -port 6381 -bind 0.0.0.0 -daemonize yes - -cluster-enabled yes -cluster-config-file /opt/redis/redis-5.0.4/cluster/6381/6381.conf -cluster-node-timeout 10000 - -appendonly yes -dir /opt/redis/redis-5.0.4/cluster/6381 -pidfile /var/run/redis-cluster/redis-6381.pid -logfile /opt/redis/redis-5.0.4/cluster/6381/6381.log \ No newline at end of file diff --git a/codes/linux/soft/config/redis/6382/redis.conf b/codes/linux/soft/config/redis/6382/redis.conf deleted file mode 100644 index 6ca21ea..0000000 --- a/codes/linux/soft/config/redis/6382/redis.conf +++ /dev/null @@ -1,12 +0,0 @@ -port 6382 -bind 0.0.0.0 -daemonize yes - -cluster-enabled yes -cluster-config-file /opt/redis/redis-5.0.4/cluster/6382/6382.conf -cluster-node-timeout 10000 - -appendonly yes -dir /opt/redis/redis-5.0.4/cluster/6382 -pidfile /var/run/redis-cluster/redis-6382.pid -logfile /opt/redis/redis-5.0.4/cluster/6382/6382.log \ No newline at end of file diff --git a/codes/linux/soft/config/redis/6383/redis.conf b/codes/linux/soft/config/redis/6383/redis.conf deleted file mode 100644 index 509f9d3..0000000 --- a/codes/linux/soft/config/redis/6383/redis.conf +++ /dev/null @@ -1,12 +0,0 @@ -port 6383 -bind 0.0.0.0 -daemonize yes - -cluster-enabled yes -cluster-config-file /opt/redis/redis-5.0.4/cluster/6383/6383.conf -cluster-node-timeout 10000 - -appendonly yes -dir /opt/redis/redis-5.0.4/cluster/6383 -pidfile /var/run/redis-cluster/redis-6383.pid -logfile /opt/redis/redis-5.0.4/cluster/6383/6383.log diff --git a/codes/linux/soft/config/redis/6384/redis.conf b/codes/linux/soft/config/redis/6384/redis.conf deleted file mode 100644 index 10a64db..0000000 --- a/codes/linux/soft/config/redis/6384/redis.conf +++ /dev/null @@ -1,12 +0,0 @@ -port 6384 -bind 0.0.0.0 -daemonize yes - -cluster-enabled yes -cluster-config-file /opt/redis/redis-5.0.4/cluster/6384/6384.conf -cluster-node-timeout 10000 - -appendonly yes -dir /opt/redis/redis-5.0.4/cluster/6384 -pidfile /var/run/redis-cluster/redis-6384.pid -logfile /opt/redis/redis-5.0.4/cluster/6384/6384.log diff --git a/codes/linux/soft/config/redis/6385/redis.conf b/codes/linux/soft/config/redis/6385/redis.conf deleted file mode 100644 index 33b66a6..0000000 --- a/codes/linux/soft/config/redis/6385/redis.conf +++ /dev/null @@ -1,12 +0,0 @@ -port 6385 -bind 0.0.0.0 -daemonize yes - -cluster-enabled yes -cluster-config-file /opt/redis/redis-5.0.4/cluster/6385/6385.conf -cluster-node-timeout 10000 - -appendonly yes -dir /opt/redis/redis-5.0.4/cluster/6385 -pidfile /var/run/redis-cluster/redis-6385.pid -logfile /opt/redis/redis-5.0.4/cluster/6385/6385.log diff --git a/codes/linux/soft/config/redis/6386/redis.conf b/codes/linux/soft/config/redis/6386/redis.conf deleted file mode 100644 index 21af861..0000000 --- a/codes/linux/soft/config/redis/6386/redis.conf +++ /dev/null @@ -1,12 +0,0 @@ -port 6386 -bind 0.0.0.0 -daemonize yes - -cluster-enabled yes -cluster-config-file /opt/redis/redis-5.0.4/cluster/6386/6386.conf -cluster-node-timeout 10000 - -appendonly yes -dir /opt/redis/redis-5.0.4/cluster/6386 -pidfile /var/run/redis-cluster/redis-6386.pid -logfile /opt/redis/redis-5.0.4/cluster/6386/6386.log diff --git a/codes/linux/soft/config/redis/boot.sh b/codes/linux/soft/config/redis/boot.sh deleted file mode 100644 index 731bd46..0000000 --- a/codes/linux/soft/config/redis/boot.sh +++ /dev/null @@ -1,7 +0,0 @@ - -/opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/6381/redis.conf -/opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/6382/redis.conf -/opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/6383/redis.conf -/opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/6384/redis.conf -/opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/6385/redis.conf -/opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/6386/redis.conf diff --git a/codes/linux/soft/config/redis/cluster/6381/redis.conf b/codes/linux/soft/config/redis/cluster/6381/redis.conf new file mode 100644 index 0000000..943eff0 --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/6381/redis.conf @@ -0,0 +1,12 @@ +port 6381 +bind 0.0.0.0 +daemonize yes + +cluster-enabled yes +cluster-config-file /usr/local/redis/cluster/6381/6381.conf +cluster-node-timeout 10000 + +appendonly yes +dir /usr/local/redis/cluster/6381 +pidfile /var/run/redis/redis-6381.pid +logfile /usr/local/redis/cluster/6381/6381.log diff --git a/codes/linux/soft/config/redis/cluster/6382/redis.conf b/codes/linux/soft/config/redis/cluster/6382/redis.conf new file mode 100644 index 0000000..7f1406c --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/6382/redis.conf @@ -0,0 +1,12 @@ +port 6382 +bind 0.0.0.0 +daemonize yes + +cluster-enabled yes +cluster-config-file /usr/local/redis/cluster/6382/6382.conf +cluster-node-timeout 10000 + +appendonly yes +dir /usr/local/redis/cluster/6382 +pidfile /var/run/redis/redis-6382.pid +logfile /usr/local/redis/cluster/6382/6382.log diff --git a/codes/linux/soft/config/redis/cluster/6383/redis.conf b/codes/linux/soft/config/redis/cluster/6383/redis.conf new file mode 100644 index 0000000..22d2aa8 --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/6383/redis.conf @@ -0,0 +1,12 @@ +port 6383 +bind 0.0.0.0 +daemonize yes + +cluster-enabled yes +cluster-config-file /usr/local/redis/cluster/6383/6383.conf +cluster-node-timeout 10000 + +appendonly yes +dir /usr/local/redis/cluster/6383 +pidfile /var/run/redis/redis-6383.pid +logfile /usr/local/redis/cluster/6383/6383.log diff --git a/codes/linux/soft/config/redis/cluster/6384/redis.conf b/codes/linux/soft/config/redis/cluster/6384/redis.conf new file mode 100644 index 0000000..b2756e6 --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/6384/redis.conf @@ -0,0 +1,12 @@ +port 6384 +bind 0.0.0.0 +daemonize yes + +cluster-enabled yes +cluster-config-file /usr/local/redis/cluster/6384/6384.conf +cluster-node-timeout 10000 + +appendonly yes +dir /usr/local/redis/cluster/6384 +pidfile /var/run/redis/redis-6384.pid +logfile /usr/local/redis/cluster/6384/6384.log diff --git a/codes/linux/soft/config/redis/cluster/6385/redis.conf b/codes/linux/soft/config/redis/cluster/6385/redis.conf new file mode 100644 index 0000000..28d36cf --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/6385/redis.conf @@ -0,0 +1,12 @@ +port 6385 +bind 0.0.0.0 +daemonize yes + +cluster-enabled yes +cluster-config-file /usr/local/redis/cluster/6385/6385.conf +cluster-node-timeout 10000 + +appendonly yes +dir /usr/local/redis/cluster/6385 +pidfile /var/run/redis/redis-6385.pid +logfile /usr/local/redis/cluster/6385/6385.log diff --git a/codes/linux/soft/config/redis/cluster/6386/redis.conf b/codes/linux/soft/config/redis/cluster/6386/redis.conf new file mode 100644 index 0000000..5ab8bf7 --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/6386/redis.conf @@ -0,0 +1,12 @@ +port 6386 +bind 0.0.0.0 +daemonize yes + +cluster-enabled yes +cluster-config-file /usr/local/redis/cluster/6386/6386.conf +cluster-node-timeout 10000 + +appendonly yes +dir /usr/local/redis/cluster/6386 +pidfile /var/run/redis/redis-6386.pid +logfile /usr/local/redis/cluster/6386/6386.log diff --git a/codes/linux/soft/config/redis/cluster/redis-cluster.sh b/codes/linux/soft/config/redis/cluster/redis-cluster.sh new file mode 100644 index 0000000..23a0051 --- /dev/null +++ b/codes/linux/soft/config/redis/cluster/redis-cluster.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash + +# --------------------------------------------------------------------------------- +# 控制台颜色 +BLACK="\033[1;30m" +RED="\033[1;31m" +GREEN="\033[1;32m" +YELLOW="\033[1;33m" +BLUE="\033[1;34m" +PURPLE="\033[1;35m" +CYAN="\033[1;36m" +RESET="$(tput sgr0)" +# --------------------------------------------------------------------------------- + +printf "${BLUE}\n" +cat << EOF +################################################################################### +# Redis 集群控制脚本 +# @system: 适用于 CentOS7+ +# @author: Zhang Peng +################################################################################### +EOF +printf "${RESET}\n" + +# Settings +PORT=6380 +NODES=6 +ENDPORT=$((PORT + NODES)) +TIMEOUT=2000 +REPLICAS=0 +PATH="/usr/local/redis" + +######################################## MAIN ######################################## +printf "${PURPLE}\n" +printf "Usage: $0 [start|create|stop|watch|tail|clean]\n" +printf "start -- Launch Redis Cluster instances.\n" +printf "create -- Create a cluster using redis-cli --cluster create.\n" +printf "stop -- Stop Redis Cluster instances.\n" +printf "watch -- Show CLUSTER NODES output (first 30 lines) of first node.\n" +printf "tail -- Run tail -f of instance at base port + ID.\n" +printf "clean -- Remove all instances data, logs, configs.\n" +printf "clean-logs -- Remove just instances logs.\n" +printf "${RESET}\n" + +case $1 in + "start") + while [[ $((PORT < ENDPORT)) != "0" ]]; do + PORT=$((PORT + 1)) + echo "Starting $PORT" + if [[ -e "${PATH}/cluster/${PORT}/redis.conf" ]]; then + ${PATH}/src/redis-server "${PATH}/cluster/${PORT}/redis.conf" + fi + done + ;; + "create") + HOSTS="" + while [[ $((PORT < ENDPORT)) != "0" ]]; do + PORT=$((PORT + 1)) + HOSTS="$HOSTS 127.0.0.1:$PORT" + done + ${PATH}/src/redis-cli --cluster create $HOSTS --cluster-replicas $REPLICAS + ;; + "stop") + while [[ $((PORT < ENDPORT)) != "0" ]]; do + PORT=$((PORT + 1)) + echo "Stopping $PORT" + ${PATH}/src/redis-cli -p $PORT shutdown nosave + done + ;; + "watch") + PORT=$((PORT + 1)) + while [[ 1 ]]; do + clear + date + ${PATH}/src/redis-cli -p $PORT cluster nodes | head -30 + sleep 1 + done + ;; + "tail") + INSTANCE=$2 + PORT=$((PORT + INSTANCE)) + tail -f ${PORT}.log + ;; + "call") + while [[ $((PORT < ENDPORT)) != "0" ]]; do + PORT=$((PORT + 1)) + ${PATH}/src/redis-cli -p $PORT $2 $3 $4 $5 $6 $7 $8 $9 + done + ;; + "clean") + rm -rf **/*.log + rm -rf **/appendonly*.aof + rm -rf **/dump*.rdb + rm -rf **/nodes*.conf + ;; + "clean-logs") + rm -rf **/*.log + ;; + "exit") + printf "${RED}Invalid option!${RESET}\n" + main + exit 0 + ;; +esac diff --git a/codes/linux/soft/config/redis/create-cluster b/codes/linux/soft/config/redis/create-cluster deleted file mode 100644 index 3de8152..0000000 --- a/codes/linux/soft/config/redis/create-cluster +++ /dev/null @@ -1,102 +0,0 @@ -#!/bin/bash - -# Settings -PORT=6380 -TIMEOUT=2000 -NODES=6 -REPLICAS=1 - -# You may want to put the above config parameters into config.sh in order to -# override the defaults without modifying this script. - -if [ -a config.sh ] -then - source "config.sh" -fi - -# Computed vars -ENDPORT=$((PORT+NODES)) - -if [ "$1" == "start" ] -then - while [ $((PORT < ENDPORT)) != "0" ]; do - PORT=$((PORT+1)) - echo "Starting $PORT" - /opt/redis/redis-5.0.4/src/redis-server /opt/redis/redis-5.0.4/cluster/${PORT}/redis.conf - done - exit 0 -fi - -if [ "$1" == "create" ] -then - HOSTS="" - while [ $((PORT < ENDPORT)) != "0" ]; do - PORT=$((PORT+1)) - HOSTS="$HOSTS 127.0.0.1:$PORT" - done - /opt/redis/redis-5.0.4/src/redis-cli --cluster create $HOSTS --cluster-replicas $REPLICAS - exit 0 -fi - -if [ "$1" == "stop" ] -then - while [ $((PORT < ENDPORT)) != "0" ]; do - PORT=$((PORT+1)) - echo "Stopping $PORT" - /opt/redis/redis-5.0.4/src/redis-cli -p $PORT shutdown nosave - done - exit 0 -fi - -if [ "$1" == "watch" ] -then - PORT=$((PORT+1)) - while [ 1 ]; do - clear - date - /opt/redis/redis-5.0.4/src/redis-cli -p $PORT cluster nodes | head -30 - sleep 1 - done - exit 0 -fi - -if [ "$1" == "tail" ] -then - INSTANCE=$2 - PORT=$((PORT+INSTANCE)) - tail -f ${PORT}.log - exit 0 -fi - -if [ "$1" == "call" ] -then - while [ $((PORT < ENDPORT)) != "0" ]; do - PORT=$((PORT+1)) - /opt/redis/redis-5.0.4/src/redis-cli -p $PORT $2 $3 $4 $5 $6 $7 $8 $9 - done - exit 0 -fi - -if [ "$1" == "clean" ] -then - rm -rf *.log - rm -rf appendonly*.aof - rm -rf dump*.rdb - rm -rf nodes*.conf - exit 0 -fi - -if [ "$1" == "clean-logs" ] -then - rm -rf *.log - exit 0 -fi - -echo "Usage: $0 [start|create|stop|watch|tail|clean]" -echo "start -- Launch Redis Cluster instances." -echo "create -- Create a cluster using redis-cli --cluster create." -echo "stop -- Stop Redis Cluster instances." -echo "watch -- Show CLUSTER NODES output (first 30 lines) of first node." -echo "tail -- Run tail -f of instance at base port + ID." -echo "clean -- Remove all instances data, logs, configs." -echo "clean-logs -- Remove just instances logs." diff --git a/codes/linux/soft/config/redis/redis.conf b/codes/linux/soft/config/redis/redis.conf index d619954..798b879 100644 --- a/codes/linux/soft/config/redis/redis.conf +++ b/codes/linux/soft/config/redis/redis.conf @@ -155,7 +155,7 @@ supervised no # # Creating a pid file is best effort: if Redis is not able to create it # nothing bad happens, the server will start and run normally. -pidfile /var/run/redis_6379.pid +pidfile /var/run/redis/redis-6379.pid # Specify the server verbosity level. # This can be one of: diff --git a/codes/linux/soft/config/redis/redis.service b/codes/linux/soft/config/redis/redis.service index 1a96e26..5382574 100644 --- a/codes/linux/soft/config/redis/redis.service +++ b/codes/linux/soft/config/redis/redis.service @@ -4,7 +4,7 @@ After=network.target [Service] Type=forking -PIDFile=/var/run/redis_6379.pid +PIDFile=/var/run/redis/redis-6379.pid ExecStart=/usr/local/bin/redis-server /usr/local/redis/redis.conf ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s QUIT $MAINPID diff --git a/codes/linux/soft/elk/boot-elk.sh b/codes/linux/soft/elk/boot-elk.sh index 501e36e..52fed31 100644 --- a/codes/linux/soft/elk/boot-elk.sh +++ b/codes/linux/soft/elk/boot-elk.sh @@ -2,50 +2,50 @@ # 检查脚本输入参数 checkInput() { - if [ "${app}" == "" ] || [ "${oper}" == "" ]; then - echo "请输入脚本参数:name" - echo " app: 要启动的进程关键字(必填)。可选值:elasticsearch|logstash|kibana|filebeat" - echo " oper: 执行操作(必填)。可选值:start|stop" - echo "例:./boot-elk.sh logstash start" - exit 0 - fi + if [ "${app}" == "" ] || [ "${oper}" == "" ]; then + echo "请输入脚本参数:name" + echo " app: 要启动的进程关键字(必填)。可选值:elasticsearch|logstash|kibana|filebeat" + echo " oper: 执行操作(必填)。可选值:start|stop" + echo "例:./boot-elk.sh logstash start" + exit 0 + fi - if [ "${app}" != "elasticsearch" ] && [ "${app}" != "logstash" ] && [ "${app}" != "kibana" ] && [ "${app}" != "filebeat" ]; then - echo "name 输入错误" - echo "可选值:elasticsearch|logstash|kibana|filebeat" - exit 0 - fi + if [ "${app}" != "elasticsearch" ] && [ "${app}" != "logstash" ] && [ "${app}" != "kibana" ] && [ "${app}" != "filebeat" ]; then + echo "name 输入错误" + echo "可选值:elasticsearch|logstash|kibana|filebeat" + exit 0 + fi } # 检查文件是否存在,不存在则退出脚本 checkFileExist() { - if [ ! -f "$1" ] - then - echo "关键文件 $1 找不到,脚本执行结束" - exit 0 - fi + if [ ! -f "$1" ] + then + echo "关键文件 $1 找不到,脚本执行结束" + exit 0 + fi } startup() { - if [ "${app}" == "elasticsearch" ]; then - checkFileExist ${ELASTICSEARCH_BIN_PATH}/elasticsearch - nohup sh ${ELASTICSEARCH_BIN_PATH}/elasticsearch >> ${ELASTICSEARCH_BIN_PATH}/nohup.out 2>&1 & - elif [ "${app}" == "logstash" ]; then - checkFileExist ${LOGSTASH_BIN_PATH}/logstash - nohup sh ${LOGSTASH_BIN_PATH}/logstash -f ${LOGSTASH_BIN_PATH}/logstash.conf >> ${LOGSTASH_BIN_PATH}/nohup.out 2>&1 & - elif [ "${app}" == "kibana" ]; then - checkFileExist ${KIBANA_BIN_PATH}/kibana - nohup sh ${KIBANA_BIN_PATH}/kibana >> ${KIBANA_BIN_PATH}/nohup.out 2>&1 & - elif [ "${app}" == "filebeat" ]; then - checkFileExist ${FILEBEAT_PATH}/filebeat - touch ${FILEBEAT_PATH}/nohup.out - nohup ${FILEBEAT_PATH}/filebeat -e -c ${FILEBEAT_PATH}/filebeat.yml -d "publish" >> ${FILEBEAT_PATH}/nohup.out 2>&1 & - fi + if [ "${app}" == "elasticsearch" ]; then + checkFileExist ${ELASTICSEARCH_BIN_PATH}/elasticsearch + nohup sh ${ELASTICSEARCH_BIN_PATH}/elasticsearch >> ${ELASTICSEARCH_BIN_PATH}/nohup.out 2>&1 & + elif [ "${app}" == "logstash" ]; then + checkFileExist ${LOGSTASH_BIN_PATH}/logstash + nohup sh ${LOGSTASH_BIN_PATH}/logstash -f ${LOGSTASH_BIN_PATH}/logstash.conf >> ${LOGSTASH_BIN_PATH}/nohup.out 2>&1 & + elif [ "${app}" == "kibana" ]; then + checkFileExist ${KIBANA_BIN_PATH}/kibana + nohup sh ${KIBANA_BIN_PATH}/kibana >> ${KIBANA_BIN_PATH}/nohup.out 2>&1 & + elif [ "${app}" == "filebeat" ]; then + checkFileExist ${FILEBEAT_PATH}/filebeat + touch ${FILEBEAT_PATH}/nohup.out + nohup ${FILEBEAT_PATH}/filebeat -e -c ${FILEBEAT_PATH}/filebeat.yml -d "publish" >> ${FILEBEAT_PATH}/nohup.out 2>&1 & + fi } shutdown() { - pid=`ps -ef | grep java | grep ${app} | awk '{print $2}'` - kill -9 ${pid} + pid=`ps -ef | grep java | grep ${app} | awk '{print $2}'` + kill -9 ${pid} } ##############################__MAIN__######################################## @@ -60,14 +60,14 @@ FILEBEAT_PATH=/opt/elastic/filebeat-${version}-linux-x86_64 checkInput case ${oper} in - start) - echo "启动 ${app}" - startup - ;; - stop) - echo "终止 ${app}" - shutdown - ;; - *) echo "${oper} is invalid oper" ;; + start) + echo "启动 ${app}" + startup + ;; + stop) + echo "终止 ${app}" + shutdown + ;; + *) echo "${oper} is invalid oper" ;; esac diff --git a/codes/linux/soft/elk/config/filebeat.yml b/codes/linux/soft/elk/config/filebeat.yml index ce1df79..256854a 100644 --- a/codes/linux/soft/elk/config/filebeat.yml +++ b/codes/linux/soft/elk/config/filebeat.yml @@ -20,48 +20,48 @@ filebeat.prospectors: - type: log - # Change to true to enable this prospector configuration. - enabled: true + # Change to true to enable this prospector configuration. + enabled: true - # Paths that should be crawled and fetched. Glob based paths. - paths: - #- /var/log/*.log - #- c:\programdata\elasticsearch\logs\* - - /home/zp/log/*.log + # Paths that should be crawled and fetched. Glob based paths. + paths: + #- /var/log/*.log + #- c:\programdata\elasticsearch\logs\* + - /home/zp/log/*.log - # Exclude lines. A list of regular expressions to match. It drops the lines that are - # matching any regular expression from the list. - #exclude_lines: ['^DBG'] + # Exclude lines. A list of regular expressions to match. It drops the lines that are + # matching any regular expression from the list. + #exclude_lines: ['^DBG'] - # Include lines. A list of regular expressions to match. It exports the lines that are - # matching any regular expression from the list. - #include_lines: ['^ERR', '^WARN'] + # Include lines. A list of regular expressions to match. It exports the lines that are + # matching any regular expression from the list. + #include_lines: ['^ERR', '^WARN'] - # Exclude files. A list of regular expressions to match. Filebeat drops the files that - # are matching any regular expression from the list. By default, no files are dropped. - #exclude_files: ['.gz$'] + # Exclude files. A list of regular expressions to match. Filebeat drops the files that + # are matching any regular expression from the list. By default, no files are dropped. + #exclude_files: ['.gz$'] - # Optional additional fields. These fields can be freely picked - # to add additional information to the crawled log files for filtering - #fields: - # level: debug - # review: 1 + # Optional additional fields. These fields can be freely picked + # to add additional information to the crawled log files for filtering + #fields: + # level: debug + # review: 1 - ### Multiline options + ### Multiline options - # Mutiline can be used for log messages spanning multiple lines. This is common - # for Java Stack Traces or C-Line Continuation + # Mutiline can be used for log messages spanning multiple lines. This is common + # for Java Stack Traces or C-Line Continuation - # The regexp Pattern that has to be matched. The example pattern matches all lines starting with [ - #multiline.pattern: ^\[ + # The regexp Pattern that has to be matched. The example pattern matches all lines starting with [ + #multiline.pattern: ^\[ - # Defines if the pattern set under pattern should be negated or not. Default is false. - #multiline.negate: false + # Defines if the pattern set under pattern should be negated or not. Default is false. + #multiline.negate: false - # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern - # that was (not) matched before or after or as long as a pattern is not matched based on negate. - # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash - #multiline.match: after + # Match can be set to "after" or "before". It is used to define if lines should be append to a pattern + # that was (not) matched before or after or as long as a pattern is not matched based on negate. + # Note: After is the equivalent to previous and before is the equivalent to to next in Logstash + #multiline.match: after #============================= Filebeat modules =============================== diff --git a/codes/linux/soft/elk/install-elk.sh b/codes/linux/soft/elk/install-elk.sh index 9b39fec..eb96cb7 100644 --- a/codes/linux/soft/elk/install-elk.sh +++ b/codes/linux/soft/elk/install-elk.sh @@ -9,97 +9,97 @@ # 获取当前设备IP ipaddr='127.0.0.1' function getDeviceIp() { - ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') + ipaddr=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') } # 检查文件是否存在,不存在则退出脚本 checkFileExist() { - if [ ! -f "$1" ] - then - echo "关键文件 $1 找不到,脚本执行结束" - exit 0 - fi + if [ ! -f "$1" ] + then + echo "关键文件 $1 找不到,脚本执行结束" + exit 0 + fi } init() { - mkdir -p ${ELASTIC_SOFTWARE_PATH} - getDeviceIp + mkdir -p ${ELASTIC_SOFTWARE_PATH} + getDeviceIp } # 安装 elasticsearch installElasticsearch() { - cd ${ELASTIC_SOFTWARE_PATH} - wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${version}.tar.gz - tar -xzf elasticsearch-${version}.tar.gz + cd ${ELASTIC_SOFTWARE_PATH} + wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${version}.tar.gz + tar -xzf elasticsearch-${version}.tar.gz } installRuby() { - cd ${RUBY_SOFTWARE_PATH} - wget https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.0.tar.gz - tar -xzf ruby-2.5.0.tar.gz - cd ruby-2.5.0 - ./configure - make & make install + cd ${RUBY_SOFTWARE_PATH} + wget https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.0.tar.gz + tar -xzf ruby-2.5.0.tar.gz + cd ruby-2.5.0 + ./configure + make & make install } # 安装 logstash installLogstash() { - cd ${ELASTIC_SOFTWARE_PATH} - wget https://artifacts.elastic.co/downloads/logstash/logstash-${version}.tar.gz - tar -xzf logstash-${version}.tar.gz + cd ${ELASTIC_SOFTWARE_PATH} + wget https://artifacts.elastic.co/downloads/logstash/logstash-${version}.tar.gz + tar -xzf logstash-${version}.tar.gz } # 安装 kibana installKibana() { - cd ${ELASTIC_SOFTWARE_PATH} - wget https://artifacts.elastic.co/downloads/kibana/kibana-${version}-linux-x86_64.tar.gz - tar -xzf kibana-${version}-linux-x86_64.tar.gz + cd ${ELASTIC_SOFTWARE_PATH} + wget https://artifacts.elastic.co/downloads/kibana/kibana-${version}-linux-x86_64.tar.gz + tar -xzf kibana-${version}-linux-x86_64.tar.gz } # 安装 filebeat installFilebeat() { - cd ${ELASTIC_SOFTWARE_PATH} - wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-${version}-linux-x86_64.tar.gz - tar -zxf filebeat-${version}-linux-x86_64.tar.gz + cd ${ELASTIC_SOFTWARE_PATH} + wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-${version}-linux-x86_64.tar.gz + tar -zxf filebeat-${version}-linux-x86_64.tar.gz } # 替换 Elasticsearch 配置 # 1. 替换 192.168.0.1 为本机 IP replaceElasticsearchConfig() { - cp ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/config/elasticsearch.yml ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/config/elasticsearch.yml.bak - sed -i "s/#network.host: 192.168.0.1/network.host: ${IP}/g" ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/config/elasticsearch.yml - touch ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/bin/nohup.out + cp ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/config/elasticsearch.yml ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/config/elasticsearch.yml.bak + sed -i "s/#network.host: 192.168.0.1/network.host: ${IP}/g" ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/config/elasticsearch.yml + touch ${ELASTIC_SOFTWARE_PATH}/elasticsearch-${version}/bin/nohup.out } replaceLogstashConfig() { - cp ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/config/logstash.yml ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/config/logstash.yml.bak - sed -i "s/# http.host: \"127.0.0.1\"/ http.host: ${IP}/g" ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/config/logstash.yml - touch ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/bin/nohup.out - cd ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/bin - wget "https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/soft/elk/config/logstash.conf" + cp ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/config/logstash.yml ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/config/logstash.yml.bak + sed -i "s/# http.host: \"127.0.0.1\"/ http.host: ${IP}/g" ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/config/logstash.yml + touch ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/bin/nohup.out + cd ${ELASTIC_SOFTWARE_PATH}/logstash-${version}/bin + wget "https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/soft/elk/config/logstash.conf" } # 替换 Kibana 配置 # 1. 替换 localhost 为本机 IP replaceKibanaConfig() { - cp ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml.bak - sed -i "s/#server.host: \"localhost\"/server.host: ${IP}/g" ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml - sed -i "s/#elasticsearch.url: \"http://localhost:9200\"/#elasticsearch.url: \"${IP}\"/g" ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml - touch ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/bin/nohup.out + cp ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml.bak + sed -i "s/#server.host: \"localhost\"/server.host: ${IP}/g" ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml + sed -i "s/#elasticsearch.url: \"http://localhost:9200\"/#elasticsearch.url: \"${IP}\"/g" ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/config/kibana.yml + touch ${ELASTIC_SOFTWARE_PATH}/kibana-${version}-linux-x86_64/bin/nohup.out } # 替换 Filebeat 配置 replaceFilebeatConfig() { - cp ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64/filebeat.yml ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64/filebeat.yml.bak - cd ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64 - wget https://github.com/dunwu/OS/blob/master/codes/deploy/tool/elk/config/filebeat.yml - sed -i 's/127.0.0.1/'"${IP}"'/g' ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64/filebeat.yml + cp ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64/filebeat.yml ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64/filebeat.yml.bak + cd ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64 + wget https://github.com/dunwu/OS/blob/master/codes/deploy/tool/elk/config/filebeat.yml + sed -i 's/127.0.0.1/'"${IP}"'/g' ${ELASTIC_SOFTWARE_PATH}/filebeat-${version}-linux-x86_64/filebeat.yml } # 为 elk.elk 用户设置权限 setPrivilegeForUser() { - chown -R elk.elk ${ELASTIC_SOFTWARE_PATH} - chown -R elk.elk /var/log/ + chown -R elk.elk ${ELASTIC_SOFTWARE_PATH} + chown -R elk.elk /var/log/ } ######################################## MAIN ######################################## diff --git a/codes/linux/soft/elk/install_elasticserch.sh b/codes/linux/soft/elk/install_elasticserch.sh index 479b3e3..bae8250 100644 --- a/codes/linux/soft/elk/install_elasticserch.sh +++ b/codes/linux/soft/elk/install_elasticserch.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # auth:kaliarch # version:v1.0 @@ -31,113 +31,113 @@ echo "4: EXIT" # 选择安装软件版本 read -p "Please input your choice:" softversion if [ "${softversion}" == "1" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/elasticsearch/elasticsearch-5.4.1.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/elasticsearch/elasticsearch-5.4.1.tar.gz" elif [ "${softversion}" == "2" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/elasticsearch/elasticsearch-6.0.1.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/elasticsearch/elasticsearch-6.0.1.tar.gz" elif [ "${softversion}" == "3" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/elasticsearch/elasticsearch-6.3.1.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/elasticsearch/elasticsearch-6.3.1.tar.gz" elif [ "${softversion}" == "4" ]; then - echo "you choce channel!" - exit 1; + echo "you choce channel!" + exit 1; else - echo "input Error! Place input{1|2|3|4|5}" - exit 0; + echo "input Error! Place input{1|2|3|4|5}" + exit 0; fi # 传入内容,格式化内容输出,可以传入多个参数,用空格隔开 output_msg() { - for msg in $*; do - action $msg /bin/true - done + for msg in $*; do + action $msg /bin/true + done } # 判断命令是否存在,第一个参数 $1 为判断的命令,第二个参数为提供该命令的yum 软件包名称 check_yum_command() { - output_msg "命令检查:$1" - hash $1 > /dev/null 2>&1 - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 - else - yum -y install $2 > /dev/null 2>&1 - # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } - fi + output_msg "命令检查:$1" + hash $1 > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 + else + yum -y install $2 > /dev/null 2>&1 + # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } + fi } # 判断目录是否存在,传入目录绝对路径,可以传入多个目录 check_dir() { - output_msg "目录检查" - for dirname in $*; do - [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 - echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} - done + output_msg "目录检查" + for dirname in $*; do + [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 + echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} + done } # 下载文件并解压至安装目录,传入url链接地址 download_file() { - output_msg "下载源码包" - mkdir -p $download_path - for file in $*; do - wget $file -c -P $download_path &> /dev/null - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "下载源码包" + mkdir -p $download_path + for file in $*; do + wget $file -c -P $download_path &> /dev/null + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 解压文件,可以传入多个压缩文件绝对路径,用空格隔开,解压至安装目录 extract_file() { - output_msg "解压源码" - for file in $*; do - if [ "${file##*.}" == "gz" ]; then - tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - elif [ "${file##*.}" == "zip" ]; then - unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "解压源码" + for file in $*; do + if [ "${file##*.}" == "gz" ]; then + tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + elif [ "${file##*.}" == "zip" ]; then + unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 配置环境变量,第一个参数为添加环境变量的绝对路径 config_env() { - output_msg "环境变量配置" + output_msg "环境变量配置" - echo "export PATH=\$PATH:$1" > ${env_file} - source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} + echo "export PATH=\$PATH:$1" > ${env_file} + source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} } # 配置主机名,第一个为主机名 config_hostname() { - if [ ${sysversion} -eq 6 ]; then - hostname $1 - elif [ ${sysversion} -eq 7 ]; then - hostnamectl set-hostname $1 - else - echo "`date +%F' '%H:%M:%S` hostname $1 config fail" >> ${install_log_path}${install_log_name} - fi + if [ ${sysversion} -eq 6 ]; then + hostname $1 + elif [ ${sysversion} -eq 7 ]; then + hostnamectl set-hostname $1 + else + echo "`date +%F' '%H:%M:%S` hostname $1 config fail" >> ${install_log_path}${install_log_name} + fi } config_limits() { - output_msg "配置limits" - cat >> /etc/security/limits.conf << EOF + output_msg "配置limits" + cat >> /etc/security/limits.conf << EOF * soft nofile 65536 * hard nofile 65536 * soft nproc 65536 * hard nproc 65536 EOF - echo "vm.max_map_count = 655360" >> /etc/sysctl.conf - sysctl -p > /dev/null 2>&1 + echo "vm.max_map_count = 655360" >> /etc/sysctl.conf + sysctl -p > /dev/null 2>&1 } # 添加配置文件 add_config() { - cat > $1 << EOF + cat > $1 << EOF cluster.name: my-application node.name: ${hostname} path.data: /usr/local/elasticsearch/data @@ -149,46 +149,46 @@ EOF } config_user() { - useradd $1 > /dev/null 2>&1 - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` $1 user add success" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%S` $1 user add fail" >> ${install_log_path}${install_log_name} && exit 1 - fi - chown ${1}.${1} ${install_path}elasticsearch/ -R + useradd $1 > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` $1 user add success" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%S` $1 user add fail" >> ${install_log_path}${install_log_name} && exit 1 + fi + chown ${1}.${1} ${install_path}elasticsearch/ -R } config_jvm() { - if [ ${sys_mem} -eq 0 ]; then - sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx512m"#g" ${jvm_conf} - sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms512m"#g" ${jvm_conf} - else - sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx${sys_mem}g"#g" ${jvm_conf} - sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms${sys_mem}g"#g" ${jvm_conf} - fi + if [ ${sys_mem} -eq 0 ]; then + sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx512m"#g" ${jvm_conf} + sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms512m"#g" ${jvm_conf} + else + sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx${sys_mem}g"#g" ${jvm_conf} + sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms${sys_mem}g"#g" ${jvm_conf} + fi } main() { - check_dir $install_log_path $install_path - check_yum_command wget wget - download_file $URL - config_hostname $hostname + check_dir $install_log_path $install_path + check_yum_command wget wget + download_file $URL + config_hostname $hostname - software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') - for filename in `ls $download_path`; do - extract_file ${download_path}$filename - done + software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') + for filename in `ls $download_path`; do + extract_file ${download_path}$filename + done - rm -fr ${download_path} - ln -s $install_path$software_name ${install_path}elasticsearch - add_config $software_config_file - check_dir ${install_path}elasticsearch/{data,logs} - config_user elasticsearch - config_env ${install_path}elasticsearch/bin - config_limits - config_jvm - echo "请使用一下命令启动服务:'su - elasticsearch -c 'nohup /usr/local/elasticsearch/bin/elasticsearch &'" + rm -fr ${download_path} + ln -s $install_path$software_name ${install_path}elasticsearch + add_config $software_config_file + check_dir ${install_path}elasticsearch/{data,logs} + config_user elasticsearch + config_env ${install_path}elasticsearch/bin + config_limits + config_jvm + echo "请使用一下命令启动服务:'su - elasticsearch -c 'nohup /usr/local/elasticsearch/bin/elasticsearch &'" } diff --git a/codes/linux/soft/elk/install_filebeat.sh b/codes/linux/soft/elk/install_filebeat.sh index bd8265e..812f81c 100644 --- a/codes/linux/soft/elk/install_filebeat.sh +++ b/codes/linux/soft/elk/install_filebeat.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # auth:kaliarch # version:v1.0 @@ -28,88 +28,88 @@ echo "4: EXIT" # 选择安装软件版本 read -p "Please input your choice:" softversion if [ "${softversion}" == "1" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/filebeat/filebeat-5.6.1-linux-x86_64.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/filebeat/filebeat-5.6.1-linux-x86_64.tar.gz" elif [ "${softversion}" == "2" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/filebeat/filebeat-6.1.3-linux-x86_64.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/filebeat/filebeat-6.1.3-linux-x86_64.tar.gz" elif [ "${softversion}" == "3" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/filebeat/filebeat-6.3.2-linux-x86_64.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/filebeat/filebeat-6.3.2-linux-x86_64.tar.gz" elif [ "${softversion}" == "4" ]; then - echo "you choce channel!" - exit 1; + echo "you choce channel!" + exit 1; else - echo "input Error! Place input{1|2|3|4}" - exit 0; + echo "input Error! Place input{1|2|3|4}" + exit 0; fi # 传入内容,格式化内容输出,可以传入多个参数,用空格隔开 output_msg() { - for msg in $*; do - action $msg /bin/true - done + for msg in $*; do + action $msg /bin/true + done } # 判断命令是否存在,第一个参数 $1 为判断的命令,第二个参数为提供该命令的yum 软件包名称 check_yum_command() { - output_msg "命令检查:$1" - hash $1 > /dev/null 2>&1 - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 - else - yum -y install $2 > /dev/null 2>&1 - # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } - fi + output_msg "命令检查:$1" + hash $1 > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 + else + yum -y install $2 > /dev/null 2>&1 + # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } + fi } # 判断目录是否存在,传入目录绝对路径,可以传入多个目录 check_dir() { - output_msg "目录检查" - for dirname in $*; do - [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 - echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} - done + output_msg "目录检查" + for dirname in $*; do + [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 + echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} + done } # 下载文件并解压至安装目录,传入url链接地址 download_file() { - output_msg "下载源码包" - mkdir -p $download_path - for file in $*; do - wget $file -c -P $download_path &> /dev/null - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "下载源码包" + mkdir -p $download_path + for file in $*; do + wget $file -c -P $download_path &> /dev/null + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 解压文件,可以传入多个压缩文件绝对路径,用空格隔开,解压至安装目录 extract_file() { - output_msg "解压源码" - for file in $*; do - if [ "${file##*.}" == "gz" ]; then - tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - elif [ "${file##*.}" == "zip" ]; then - unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "解压源码" + for file in $*; do + if [ "${file##*.}" == "gz" ]; then + tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + elif [ "${file##*.}" == "zip" ]; then + unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 配置环境变量,第一个参数为添加环境变量的绝对路径 config_env() { - output_msg "环境变量配置" - echo "export PATH=\$PATH:$1" > ${env_file} - source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} + output_msg "环境变量配置" + echo "export PATH=\$PATH:$1" > ${env_file} + source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} } # 添加配置文件 add_config() { - cat > $1 << EOF + cat > $1 << EOF filebeat.prospectors: - input_type: log paths: @@ -120,17 +120,17 @@ EOF } main() { - check_dir $install_log_path $install_path - check_yum_command wget wget - download_file $URL + check_dir $install_log_path $install_path + check_yum_command wget wget + download_file $URL - software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') - for filename in `ls $download_path`; do - extract_file ${download_path}$filename - done - rm -fr ${download_path} - ln -s $install_path$software_name ${install_path}filebeat - add_config ${software_config_file} + software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') + for filename in `ls $download_path`; do + extract_file ${download_path}$filename + done + rm -fr ${download_path} + ln -s $install_path$software_name ${install_path}filebeat + add_config ${software_config_file} } main diff --git a/codes/linux/soft/elk/install_kibana.sh b/codes/linux/soft/elk/install_kibana.sh index 7359d2d..7e77ecb 100644 --- a/codes/linux/soft/elk/install_kibana.sh +++ b/codes/linux/soft/elk/install_kibana.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # auth:kaliarch # version:v1.0 @@ -28,88 +28,88 @@ echo "4: EXIT" # 选择安装软件版本 read -p "Please input your choice:" softversion if [ "${softversion}" == "1" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/kibana/kibana-6.0.1-linux-x86_64.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/kibana/kibana-6.0.1-linux-x86_64.tar.gz" elif [ "${softversion}" == "2" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/kibana/kibana-6.2.4-linux-x86_64.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/kibana/kibana-6.2.4-linux-x86_64.tar.gz" elif [ "${softversion}" == "3" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/kibana/kibana-6.3.1-linux-x86_64.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/kibana/kibana-6.3.1-linux-x86_64.tar.gz" elif [ "${softversion}" == "4" ]; then - echo "you choce channel!" - exit 1; + echo "you choce channel!" + exit 1; else - echo "input Error! Place input{1|2|3|4}" - exit 0; + echo "input Error! Place input{1|2|3|4}" + exit 0; fi # 传入内容,格式化内容输出,可以传入多个参数,用空格隔开 output_msg() { - for msg in $*; do - action $msg /bin/true - done + for msg in $*; do + action $msg /bin/true + done } # 判断命令是否存在,第一个参数 $1 为判断的命令,第二个参数为提供该命令的yum 软件包名称 check_yum_command() { - output_msg "命令检查:$1" - hash $1 > /dev/null 2>&1 - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 - else - yum -y install $2 > /dev/null 2>&1 - # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } - fi + output_msg "命令检查:$1" + hash $1 > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 + else + yum -y install $2 > /dev/null 2>&1 + # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } + fi } # 判断目录是否存在,传入目录绝对路径,可以传入多个目录 check_dir() { - output_msg "目录检查" - for dirname in $*; do - [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 - echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} - done + output_msg "目录检查" + for dirname in $*; do + [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 + echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} + done } # 下载文件并解压至安装目录,传入url链接地址 download_file() { - output_msg "下载源码包" - mkdir -p $download_path - for file in $*; do - wget $file -c -P $download_path &> /dev/null - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "下载源码包" + mkdir -p $download_path + for file in $*; do + wget $file -c -P $download_path &> /dev/null + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 解压文件,可以传入多个压缩文件绝对路径,用空格隔开,解压至安装目录 extract_file() { - output_msg "解压源码" - for file in $*; do - if [ "${file##*.}" == "gz" ]; then - tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - elif [ "${file##*.}" == "zip" ]; then - unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "解压源码" + for file in $*; do + if [ "${file##*.}" == "gz" ]; then + tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + elif [ "${file##*.}" == "zip" ]; then + unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 配置环境变量,第一个参数为添加环境变量的绝对路径 config_env() { - output_msg "环境变量配置" - echo "export PATH=\$PATH:$1" > ${env_file} - source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} + output_msg "环境变量配置" + echo "export PATH=\$PATH:$1" > ${env_file} + source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} } # 添加配置文件 add_config() { - cat > $1 << EOF + cat > $1 << EOF server.port: 5601 server.host: "0.0.0.0" elasticsearch.url: "http://127.0.0.1:9200" @@ -117,18 +117,18 @@ EOF } main() { - check_dir $install_log_path $install_path - check_yum_command wget wget - download_file $URL + check_dir $install_log_path $install_path + check_yum_command wget wget + download_file $URL - software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') - for filename in `ls $download_path`; do - extract_file ${download_path}$filename - done - rm -fr ${download_path} - ln -s ${install_path}$software_name ${install_path}kibana - add_config ${software_config_file} - config_env ${install_path}kibana/bin + software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') + for filename in `ls $download_path`; do + extract_file ${download_path}$filename + done + rm -fr ${download_path} + ln -s ${install_path}$software_name ${install_path}kibana + add_config ${software_config_file} + config_env ${install_path}kibana/bin } main diff --git a/codes/linux/soft/elk/install_logstash.sh b/codes/linux/soft/elk/install_logstash.sh index 7300bff..92546af 100644 --- a/codes/linux/soft/elk/install_logstash.sh +++ b/codes/linux/soft/elk/install_logstash.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # auth:kaliarch # version:v1.0 @@ -28,88 +28,88 @@ echo "4: EXIT" # 选择安装软件版本 read -p "Please input your choice:" softversion if [ "${softversion}" == "1" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/logstash/logstash-5.4.1.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/logstash/logstash-5.4.1.tar.gz" elif [ "${softversion}" == "2" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/logstash/logstash-6.1.3.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/logstash/logstash-6.1.3.tar.gz" elif [ "${softversion}" == "3" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/logstash/logstash-6.3.2.tar.gz" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/logstash/logstash-6.3.2.tar.gz" elif [ "${softversion}" == "4" ]; then - echo "you choce channel!" - exit 1; + echo "you choce channel!" + exit 1; else - echo "input Error! Place input{1|2|3|4}" - exit 0; + echo "input Error! Place input{1|2|3|4}" + exit 0; fi # 传入内容,格式化内容输出,可以传入多个参数,用空格隔开 output_msg() { - for msg in $*; do - action $msg /bin/true - done + for msg in $*; do + action $msg /bin/true + done } # 判断命令是否存在,第一个参数 $1 为判断的命令,第二个参数为提供该命令的yum 软件包名称 check_yum_command() { - output_msg "命令检查:$1" - hash $1 > /dev/null 2>&1 - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 - else - yum -y install $2 > /dev/null 2>&1 - # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } - fi + output_msg "命令检查:$1" + hash $1 > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 + else + yum -y install $2 > /dev/null 2>&1 + # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } + fi } # 判断目录是否存在,传入目录绝对路径,可以传入多个目录 check_dir() { - output_msg "目录检查" - for dirname in $*; do - [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 - echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} - done + output_msg "目录检查" + for dirname in $*; do + [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 + echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} + done } # 下载文件并解压至安装目录,传入url链接地址 download_file() { - output_msg "下载源码包" - mkdir -p $download_path - for file in $*; do - wget $file -c -P $download_path &> /dev/null - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "下载源码包" + mkdir -p $download_path + for file in $*; do + wget $file -c -P $download_path &> /dev/null + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 解压文件,可以传入多个压缩文件绝对路径,用空格隔开,解压至安装目录 extract_file() { - output_msg "解压源码" - for file in $*; do - if [ "${file##*.}" == "gz" ]; then - tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - elif [ "${file##*.}" == "zip" ]; then - unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "解压源码" + for file in $*; do + if [ "${file##*.}" == "gz" ]; then + tar -zxf $file -C $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + elif [ "${file##*.}" == "zip" ]; then + unzip -q $file -d $install_path && echo "`date +%F' '%H:%M:%S` $file extrac success!,path is $install_path" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%S` $file type error, extrac fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 配置环境变量,第一个参数为添加环境变量的绝对路径 config_env() { - output_msg "环境变量配置" - echo "export PATH=\$PATH:$1" > ${env_file} - source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} + output_msg "环境变量配置" + echo "export PATH=\$PATH:$1" > ${env_file} + source ${env_file} && echo "`date +%F' '%H:%M:%S` 软件安装完成!" >> ${install_log_path}${install_log_name} } # 添加配置文件 add_config() { - cat > $1 << EOF + cat > $1 << EOF input { beats { port => "5044" @@ -125,18 +125,18 @@ EOF } main() { - check_dir $install_log_path $install_path - check_yum_command wget wget - download_file $URL + check_dir $install_log_path $install_path + check_yum_command wget wget + download_file $URL - software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') - for filename in `ls $download_path`; do - extract_file ${download_path}$filename - done - rm -fr ${download_path} - ln -s $install_path$software_name ${install_path}logstash - add_config ${software_config_file} - config_env ${install_path}logstash/bin + software_name=$(echo $URL | awk -F'/' '{print $NF}' | awk -F'.tar.gz' '{print $1}') + for filename in `ls $download_path`; do + extract_file ${download_path}$filename + done + rm -fr ${download_path} + ln -s $install_path$software_name ${install_path}logstash + add_config ${software_config_file} + config_env ${install_path}logstash/bin } main diff --git a/codes/linux/soft/fastdfs-install.sh b/codes/linux/soft/fastdfs-install.sh index 65617f6..95cfb00 100644 --- a/codes/linux/soft/fastdfs-install.sh +++ b/codes/linux/soft/fastdfs-install.sh @@ -28,21 +28,25 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install fastdfs begin.${RESET}\n" -command -v yum > /dev/null 2>&1 || { printf "${RED}Require yum but it's not installed.${RESET}\n"; - exit 1; } -command -v git > /dev/null 2>&1 || { printf "${RED}Require git but it's not installed.${RESET}\n"; - exit 1; } +command -v yum > /dev/null 2>&1 || { + printf "${RED}Require yum but it's not installed.${RESET}\n"; + exit 1; +} +command -v git > /dev/null 2>&1 || { + printf "${RED}Require git but it's not installed.${RESET}\n"; + exit 1; +} if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh fastdfs-install.sh [path]\n" - printf "\t Example: sh fastdfs-install.sh /opt/fastdfs\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh fastdfs-install.sh [path]\n" + printf "\t Example: sh fastdfs-install.sh /opt/fastdfs\n" + printf "${RESET}\n" fi path=/opt/fdfs if [[ -n $1 ]]; then - path=$1 + path=$1 fi nginx_version=1.16.0 @@ -57,8 +61,8 @@ path=/opt/fdfs mkdir -p ${path}/libfastcommon curl -o ${path}/libfastcommon.zip http://dunwu.test.upcdn.net/soft/fdfs/libfastcommon.zip if [[ ! -f ${path}/libfastcommon.zip ]]; then - printf "${RED}[Error]install libfastcommon failed,exit. ${RESET}\n" - exit 1 + printf "${RED}[Error]install libfastcommon failed,exit. ${RESET}\n" + exit 1 fi unzip -o ${path}/libfastcommon.zip -d ${path} @@ -71,7 +75,7 @@ printf "${GREEN}>>>>>>>>> install fastdfs${RESET}" mkdir -p ${path}/fastdfs curl -o ${path}/fastdfs.zip http://dunwu.test.upcdn.net/soft/fdfs/fastdfs.zip if [[ ! -f ${path}/fastdfs.zip ]]; then - printf "${RED}>>>>>>>>> install fastdfs failed,exit. ${RESET}\n" + printf "${RED}>>>>>>>>> install fastdfs failed,exit. ${RESET}\n" fi unzip -o ${path}/fastdfs.zip -d ${path} cd ${path}/fastdfs @@ -82,7 +86,7 @@ printf "${GREEN}>>>>>>>>> install fastdfs-nginx-module${RESET}\n" mkdir -p ${path}/fastdfs-nginx-module curl -o ${path}/fastdfs-nginx-module.zip http://dunwu.test.upcdn.net/soft/fdfs/fastdfs-nginx-module.zip if [[ ! -f ${path}/fastdfs-nginx-module.zip ]]; then - printf "${RED}>>>>>>>>> install fastdfs-nginx-module failed,exit. ${RESET}\n" + printf "${RED}>>>>>>>>> install fastdfs-nginx-module failed,exit. ${RESET}\n" fi unzip -o ${path}/fastdfs-nginx-module.zip -d ${path} diff --git a/codes/linux/soft/install_grafana.sh b/codes/linux/soft/install_grafana.sh index 1a235db..4364429 100644 --- a/codes/linux/soft/install_grafana.sh +++ b/codes/linux/soft/install_grafana.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # auth:kaliarch # version:v1.0 @@ -27,84 +27,84 @@ echo "4: EXIT" # 选择安装软件版本 read -p "Please input your choice:" softversion if [ "${softversion}" == "1" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/grafana/grafana-5.1.0-1.x86_64.rpm" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/grafana/grafana-5.1.0-1.x86_64.rpm" elif [ "${softversion}" == "2" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/grafana/grafana-5.1.5-1.x86_64.rpm" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/grafana/grafana-5.1.5-1.x86_64.rpm" elif [ "${softversion}" == "3" ]; then - URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/grafana/grafana-5.2.2-1.x86_64.rpm" + URL="https://anchnet-script.oss-cn-shanghai.aliyuncs.com/grafana/grafana-5.2.2-1.x86_64.rpm" elif [ "${softversion}" == "4" ]; then - echo "you choce channel!" - exit 1; + echo "you choce channel!" + exit 1; else - echo "input Error! Place input{1|2|3|4}" - exit 0; + echo "input Error! Place input{1|2|3|4}" + exit 0; fi # 传入内容,格式化内容输出,可以传入多个参数,用空格隔开 output_msg() { - for msg in $*; do - action $msg /bin/true - done + for msg in $*; do + action $msg /bin/true + done } # 判断命令是否存在,第一个参数 $1 为判断的命令,第二个参数为提供该命令的yum 软件包名称 check_yum_command() { - output_msg "命令检查:$1" - hash $1 > /dev/null 2>&1 - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 - else - yum -y install $2 > /dev/null 2>&1 - # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } - fi + output_msg "命令检查:$1" + hash $1 > /dev/null 2>&1 + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` check command $1 " >> ${install_log_path}${install_log_name} && return 0 + else + yum -y install $2 > /dev/null 2>&1 + # hash $Command || { echo "`date +%F' '%H:%M:%S` $2 is installed fail">>${install_log_path}${install_log_name} ; exit 1 } + fi } # 判断目录是否存在,传入目录绝对路径,可以传入多个目录 check_dir() { - output_msg "目录检查" - for dirname in $*; do - [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 - echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} - done + output_msg "目录检查" + for dirname in $*; do + [ -d $dirname ] || mkdir -p $dirname > /dev/null 2>&1 + echo "`date +%F' '%H:%M:%S` $dirname check success!" >> ${install_log_path}${install_log_name} + done } # 下载文件并解压至安装目录,传入url链接地址 download_file() { - output_msg "下载源码包" - mkdir -p $download_path - for file in $*; do - wget $file -c -P $download_path &> /dev/null - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 - fi - done + output_msg "下载源码包" + mkdir -p $download_path + for file in $*; do + wget $file -c -P $download_path &> /dev/null + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` $file download success!" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%s` $file download fail!" >> ${install_log_path}${install_log_name} && exit 1 + fi + done } # 安装grafana插件,传入安装的插件的名称 install_grafana_plugins() { - output_msg "grafana插件安装" - check_yum_command grafana-cli - grafana-cli plugins install $* > /dev/null - if [ $? -eq 0 ]; then - echo "`date +%F' '%H:%M:%S` grafana plugins $* install success!" >> ${install_log_path}${install_log_name} - else - echo "`date +%F' '%H:%M:%s` grafana plugins $* install success!" >> ${install_log_path}${install_log_name} && exit 1 - fi + output_msg "grafana插件安装" + check_yum_command grafana-cli + grafana-cli plugins install $* > /dev/null + if [ $? -eq 0 ]; then + echo "`date +%F' '%H:%M:%S` grafana plugins $* install success!" >> ${install_log_path}${install_log_name} + else + echo "`date +%F' '%H:%M:%s` grafana plugins $* install success!" >> ${install_log_path}${install_log_name} && exit 1 + fi } main() { - check_dir $install_log_path $install_path - check_yum_command wget wget - download_file $URL - for filename in `ls $download_path`; do - yum -y install $download_path$filename > /dev/null 2>&1 - done - install_grafana_plugins alexanderzobnin-zabbix-app + check_dir $install_log_path $install_path + check_yum_command wget wget + download_file $URL + for filename in `ls $download_path`; do + yum -y install $download_path$filename > /dev/null 2>&1 + done + install_grafana_plugins alexanderzobnin-zabbix-app } main diff --git a/codes/linux/soft/jdk8-install.sh b/codes/linux/soft/jdk8-install.sh index 9ac84ea..b08733e 100644 --- a/codes/linux/soft/jdk8-install.sh +++ b/codes/linux/soft/jdk8-install.sh @@ -27,8 +27,10 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install jdk8 begin.${RESET}\n" -command -v yum > /dev/null 2>&1 || { printf "${RED}Require yum but it's not installed.${RESET}\n"; - exit 1; } +command -v yum > /dev/null 2>&1 || { + printf "${RED}Require yum but it's not installed.${RESET}\n"; + exit 1; +} yum -y install java-1.8.0-openjdk-devel.x86_64 java -version diff --git a/codes/linux/soft/kafka-install.sh b/codes/linux/soft/kafka-install.sh index 6a31a87..a8cced5 100644 --- a/codes/linux/soft/kafka-install.sh +++ b/codes/linux/soft/kafka-install.sh @@ -26,24 +26,26 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install kafka begin.${RESET}\n" -command -v java > /dev/null 2>&1 || { printf "${RED}Require java but it's not installed.${RESET}\n"; - exit 1; } +command -v java > /dev/null 2>&1 || { + printf "${RED}Require java but it's not installed.${RESET}\n"; + exit 1; +} if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh kafka-install.sh [version] [path]\n" - printf "\t Example: sh kafka-install.sh 2.2.0 /opt/kafka\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh kafka-install.sh [version] [path]\n" + printf "\t Example: sh kafka-install.sh 2.2.0 /opt/kafka\n" + printf "${RESET}\n" fi version=2.2.0 if [[ -n $1 ]]; then - version=$1 + version=$1 fi path=/opt/kafka if [[ -n $2 ]]; then - path=$2 + path=$2 fi # install info diff --git a/codes/linux/soft/maven-install.sh b/codes/linux/soft/maven-install.sh index e562f71..821bcbe 100644 --- a/codes/linux/soft/maven-install.sh +++ b/codes/linux/soft/maven-install.sh @@ -28,24 +28,26 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install maven begin.${RESET}\n" -command -v java > /dev/null 2>&1 || { printf "${RED}Require java but it's not installed.${RESET}\n"; - exit 1; } +command -v java > /dev/null 2>&1 || { + printf "${RED}Require java but it's not installed.${RESET}\n"; + exit 1; +} if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh maven-install.sh [version] [path]\n" - printf "\t Example: sh maven-install.sh 3.6.0 /opt/maven\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh maven-install.sh [version] [path]\n" + printf "\t Example: sh maven-install.sh 3.6.0 /opt/maven\n" + printf "${RESET}\n" fi version=3.6.2 if [[ -n $1 ]]; then - version=$1 + version=$1 fi path=/opt/maven if [[ -n $2 ]]; then - path=$2 + path=$2 fi # install info diff --git a/codes/linux/soft/mongodb-install.sh b/codes/linux/soft/mongodb-install.sh index f92d02e..4f39bb4 100644 --- a/codes/linux/soft/mongodb-install.sh +++ b/codes/linux/soft/mongodb-install.sh @@ -27,20 +27,20 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install mongodb begin.${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh mongodb-install.sh [version] [path]\n" - printf "\t Example: sh mongodb-install.sh 4.0.9 /opt/mongodb\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh mongodb-install.sh [version] [path]\n" + printf "\t Example: sh mongodb-install.sh 4.0.9 /opt/mongodb\n" + printf "${RESET}\n" fi version=4.0.9 if [[ -n $1 ]]; then - version=$1 + version=$1 fi path=/opt/mongodb if [[ -n $2 ]]; then - path=$2 + path=$2 fi # install info diff --git a/codes/linux/soft/mysql-install.sh b/codes/linux/soft/mysql-install.sh index 0b3971b..2f96450 100644 --- a/codes/linux/soft/mysql-install.sh +++ b/codes/linux/soft/mysql-install.sh @@ -26,12 +26,18 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install mysql begin.${RESET}\n" -command -v wget > /dev/null 2>&1 || { printf "${RED}Require wget but it's not installed.${RESET}\n"; - exit 1; } -command -v rpm > /dev/null 2>&1 || { printf "${RED}Require rpm but it's not installed.${RESET}\n"; - exit 1; } -command -v yum > /dev/null 2>&1 || { printf "${RED}Require yum but it's not installed.${RESET}\n"; - exit 1; } +command -v wget > /dev/null 2>&1 || { + printf "${RED}Require wget but it's not installed.${RESET}\n"; + exit 1; +} +command -v rpm > /dev/null 2>&1 || { + printf "${RED}Require rpm but it's not installed.${RESET}\n"; + exit 1; +} +command -v yum > /dev/null 2>&1 || { + printf "${RED}Require yum but it's not installed.${RESET}\n"; + exit 1; +} # 使用 rpm 安装 mysql wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm diff --git a/codes/linux/soft/nacos-install.sh b/codes/linux/soft/nacos-install.sh index 4182859..300a69c 100644 --- a/codes/linux/soft/nacos-install.sh +++ b/codes/linux/soft/nacos-install.sh @@ -11,24 +11,28 @@ cat << EOF EOF -command -v java > /dev/null 2>&1 || { echo >&2 "Require java but it's not installed."; - exit 1; } -command -v mvn > /dev/null 2>&1 || { echo >&2 "Require mvn but it's not installed."; - exit 1; } +command -v java > /dev/null 2>&1 || { + printf "${RED}Require java but it's not installed.${RESET}\n"; + exit 1; +} +command -v mvn > /dev/null 2>&1 || { + printf "${RED}Require mvn but it's not installed.${RESET}\n"; + exit 1; +} if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - echo "Usage: sh nacos-install.sh [version] [path]" - printf "Example: sh nacos-install.sh 1.0.0 /opt/nacos\n" + echo "Usage: sh nacos-install.sh [version] [path]" + printf "Example: sh nacos-install.sh 1.0.0 /opt/nacos\n" fi version=1.0.0 if [[ -n $1 ]]; then - version=$1 + version=$1 fi root=/opt/nacos if [[ -n $2 ]]; then - root=$2 + root=$2 fi echo "Current execution: install nacos ${version} to ${root}" diff --git a/codes/linux/soft/nginx-install.sh b/codes/linux/soft/nginx-install.sh index a06f9f9..0aa0ae6 100644 --- a/codes/linux/soft/nginx-install.sh +++ b/codes/linux/soft/nginx-install.sh @@ -31,17 +31,17 @@ command -v yum > /dev/null 2>&1 || { printf "\n${GREEN}>>>>>>>> install nginx begin${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t Usage: sh nginx-install.sh [version] \n" - printf "\t Default: sh nginx-install.sh 1.16.0 \n" - printf "\t Example: sh nginx-install.sh 1.16.0 \n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t Usage: sh nginx-install.sh [version] \n" + printf "\t Default: sh nginx-install.sh 1.16.0 \n" + printf "\t Example: sh nginx-install.sh 1.16.0 \n" + printf "${RESET}\n" fi temp=/opt/nginx version=1.16.0 if [[ -n $1 ]]; then - version=$1 + version=$1 fi # install info diff --git a/codes/linux/soft/nodejs-install.sh b/codes/linux/soft/nodejs-install.sh index ca11b59..9894c3a 100644 --- a/codes/linux/soft/nodejs-install.sh +++ b/codes/linux/soft/nodejs-install.sh @@ -28,15 +28,15 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install nodejs begin.${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh nodejs-install.sh [version]\n" - printf "\t Example: sh nodejs-install.sh 10.15.2\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh nodejs-install.sh [version]\n" + printf "\t Example: sh nodejs-install.sh 10.15.2\n" + printf "${RESET}\n" fi version=10.15.2 if [[ -n $1 ]]; then - version=$1 + version=$1 fi # install info diff --git a/codes/linux/soft/redis-install.sh b/codes/linux/soft/redis-install.sh index d9e8885..b391568 100644 --- a/codes/linux/soft/redis-install.sh +++ b/codes/linux/soft/redis-install.sh @@ -31,25 +31,25 @@ printf "\n${GREEN}>>>>>>>> install redis begin${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]] || [[ $# -lt 3 ]] || [[ $# -lt 4 ]]; then printf "${PURPLE}[Hint]\n" - printf "\t Usage: sh redis-install.sh [version] [port] [password] \n" - printf "\t Default: sh redis-install.sh 5.0.4 6379 \n" - printf "\t Example: sh redis-install.sh 5.0.4 6379 123456 \n" - printf "${RESET}\n" + printf "\t Usage: sh redis-install.sh [version] [port] [password] \n" + printf "\t Default: sh redis-install.sh 5.0.4 6379 \n" + printf "\t Example: sh redis-install.sh 5.0.4 6379 123456 \n" + printf "${RESET}\n" fi version=5.0.4 if [[ -n $1 ]]; then - version=$1 + version=$1 fi port=6379 if [[ -n $2 ]]; then - port=$2 + port=$2 fi password= if [[ -n $3 ]]; then - password=$3 + password=$3 fi # install info @@ -83,8 +83,8 @@ cp ${path}/redis.conf ${path}/redis.conf.default wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/soft/config/redis/redis.conf -O ${path}/redis.conf sed -i "s/^port 6379/port ${port}/g" ${path}/redis.conf if [[ -n ${password} ]]; then - sed -i "s/^protected-mode no/protected-mode yes/g" ${path}/redis.conf - sed -i "s/^# requirepass/requirepass ${password}/g" ${path}/redis.conf + sed -i "s/^protected-mode no/protected-mode yes/g" ${path}/redis.conf + sed -i "s/^# requirepass/requirepass ${password}/g" ${path}/redis.conf fi printf "\n${CYAN}>>>> open redis port in firewall${RESET}\n" diff --git a/codes/linux/soft/rocketmq-install.sh b/codes/linux/soft/rocketmq-install.sh index cf4fff8..1087511 100644 --- a/codes/linux/soft/rocketmq-install.sh +++ b/codes/linux/soft/rocketmq-install.sh @@ -27,20 +27,20 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install tomcat begin.${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh rocketmq-install.sh [version] [path]\n" - printf "\t Example: sh rocketmq-install.sh 4.5.0 /opt/rocketmq\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh rocketmq-install.sh [version] [path]\n" + printf "\t Example: sh rocketmq-install.sh 4.5.0 /opt/rocketmq\n" + printf "${RESET}\n" fi version=4.5.0 if [[ -n $1 ]]; then - version=$1 + version=$1 fi path=/opt/rocketmq if [[ -n $2 ]]; then - path=$2 + path=$2 fi # install info diff --git a/codes/linux/soft/tomcat8-install.sh b/codes/linux/soft/tomcat8-install.sh index f967bd0..db76cda 100644 --- a/codes/linux/soft/tomcat8-install.sh +++ b/codes/linux/soft/tomcat8-install.sh @@ -27,20 +27,20 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install tomcat begin.${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh tomcat8-install.sh [version] [path]\n" - printf "\t Example: sh tomcat8-install.sh 8.5.28 /opt/tomcat8\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh tomcat8-install.sh [version] [path]\n" + printf "\t Example: sh tomcat8-install.sh 8.5.28 /opt/tomcat8\n" + printf "${RESET}\n" fi version=8.5.28 if [[ -n $1 ]]; then - version=$1 + version=$1 fi path=/opt/tomcat if [[ -n $2 ]]; then - path=$2 + path=$2 fi # install info diff --git a/codes/linux/soft/zookeeper-install.sh b/codes/linux/soft/zookeeper-install.sh index 68cacef..37fc5f4 100644 --- a/codes/linux/soft/zookeeper-install.sh +++ b/codes/linux/soft/zookeeper-install.sh @@ -27,20 +27,20 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install zookeeper begin.${RESET}\n" if [[ $# -lt 1 ]] || [[ $# -lt 2 ]]; then - printf "${PURPLE}[Hint]\n" - printf "\t sh zookeeper-install.sh [version] [path]\n" - printf "\t Example: sh zookeeper-install.sh 3.4.12 /opt/zookeeper\n" - printf "${RESET}\n" + printf "${PURPLE}[Hint]\n" + printf "\t sh zookeeper-install.sh [version] [path]\n" + printf "\t Example: sh zookeeper-install.sh 3.4.12 /opt/zookeeper\n" + printf "${RESET}\n" fi version=3.4.12 if [[ -n $1 ]]; then - version=$1 + version=$1 fi path=/opt/zookeeper if [[ -n $2 ]]; then - path=$2 + path=$2 fi # install info diff --git a/codes/linux/soft/zsh-install.sh b/codes/linux/soft/zsh-install.sh index ce7a0ec..1a01c63 100644 --- a/codes/linux/soft/zsh-install.sh +++ b/codes/linux/soft/zsh-install.sh @@ -27,10 +27,14 @@ printf "${RESET}" printf "${GREEN}>>>>>>>> install zsh begin.${RESET}\n" -command -v yum > /dev/null 2>&1 || { printf "${RED}Require yum but it's not installed.${RESET}\n"; - exit 1; } -command -v git > /dev/null 2>&1 || { printf "${RED}Require git but it's not installed.${RESET}\n"; - exit 1; } +command -v yum > /dev/null 2>&1 || { + printf "${RED}Require yum but it's not installed.${RESET}\n"; + exit 1; +} +command -v git > /dev/null 2>&1 || { + printf "${RED}Require git but it's not installed.${RESET}\n"; + exit 1; +} # install zsh yum install -y zsh diff --git a/codes/linux/sys/change-yum-repo.sh b/codes/linux/sys/change-yum-repo.sh index 9027a18..65611c8 100644 --- a/codes/linux/sys/change-yum-repo.sh +++ b/codes/linux/sys/change-yum-repo.sh @@ -33,21 +33,21 @@ version=`cat /etc/redhat-release | awk '{print substr($4,1,1)}'` # 根据发型版本选择相应 yum 镜像 if [[ ${version} == 5 ]]; then - # Cento5 已废弃,只能使用 http://vault.CentOS.org/ 替换,但由于是国外镜像,速度较慢 - wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/sys/yum/Centos-5.repo -O /etc/yum.repos.d/CentOS-Base.repo + # Cento5 已废弃,只能使用 http://vault.CentOS.org/ 替换,但由于是国外镜像,速度较慢 + wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/sys/yum/Centos-5.repo -O /etc/yum.repos.d/CentOS-Base.repo - # 根据实际发型版本情况替换 - detailVersion=`lsb_release -r | awk '{print substr($2,1,3)}'` - sed -i 's/$releasever/'"${detailVersion}"'/g' /etc/yum.repos.d/CentOS-Base.repo + # 根据实际发型版本情况替换 + detailVersion=`lsb_release -r | awk '{print substr($2,1,3)}'` + sed -i 's/$releasever/'"${detailVersion}"'/g' /etc/yum.repos.d/CentOS-Base.repo - # 不替换下面的开关,可能会出现错误:Could not open/read repomd.xml - sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/CentOS-Media.repo + # 不替换下面的开关,可能会出现错误:Could not open/read repomd.xml + sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/CentOS-Media.repo elif [[ ${version} == 6 ]]; then - wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/sys/yum/Centos-6.repo -O /etc/yum.repos.d/CentOS-Base.repo + wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/sys/yum/Centos-6.repo -O /etc/yum.repos.d/CentOS-Base.repo elif [[ ${version} == 7 ]]; then - wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/sys/yum/Centos-7.repo -O /etc/yum.repos.d/CentOS-Base.repo + wget -N https://gitee.com/turnon/linux-tutorial/raw/master/codes/linux/sys/yum/Centos-7.repo -O /etc/yum.repos.d/CentOS-Base.repo else - printf "\n${RED}版本不支持,替换 yum repo 失败${RESET}\n" + printf "\n${RED}版本不支持,替换 yum repo 失败${RESET}\n" fi # 更新缓存 diff --git a/codes/linux/sys/sys-settings.sh b/codes/linux/sys/sys-settings.sh index 96adb9b..eb93a30 100644 --- a/codes/linux/sys/sys-settings.sh +++ b/codes/linux/sys/sys-settings.sh @@ -13,57 +13,57 @@ RESET="$(tput sgr0)" # --------------------------------------------------------------------------------- printHeadInfo() { -printf "${BLUE}\n" -cat << EOF + printf "${BLUE}\n" + cat << EOF ################################################################################### # Linux Centos7 系统配置脚本(根据需要选择) # @author: Zhang Peng ################################################################################### EOF -printf "${RESET}\n" + printf "${RESET}\n" } setLimit() { -cat >> /etc/security/limits.conf << EOF + cat >> /etc/security/limits.conf << EOF * - nofile 65535 * - nproc 65535 EOF } setLang() { -cat > /etc/sysconfig/i18n << EOF + cat > /etc/sysconfig/i18n << EOF LANG="zh_CN.UTF-8" EOF } closeShutdownShortkey() { - printf "\n${CYAN}>>>> 关闭 Ctrl+Alt+Del 快捷键防止重新启动${RESET}\n" - sed -i 's#exec /sbin/shutdown -r now#\#exec /sbin/shutdown -r now#' /etc/init/control-alt-delete.conf + printf "\n${CYAN}>>>> 关闭 Ctrl+Alt+Del 快捷键防止重新启动${RESET}\n" + sed -i 's#exec /sbin/shutdown -r now#\#exec /sbin/shutdown -r now#' /etc/init/control-alt-delete.conf } closeSelinux() { - # see http://blog.51cto.com/13570193/2093299 - printf "\n${CYAN}>>>> 关闭 selinux${RESET}\n" - sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config + # see http://blog.51cto.com/13570193/2093299 + printf "\n${CYAN}>>>> 关闭 selinux${RESET}\n" + sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config } setBootMode() { - # 1. 停机(记得不要把 initdefault 配置为 0,因为这样会使 Linux 不能启动) - # 2. 单用户模式,就像 Win9X 下的安全模式 - # 3. 多用户,但是没有 NFS - # 4. 完全多用户模式,准则的运行级 - # 5. 通常不用,在一些特殊情况下可以用它来做一些事情 - # 6. X11,即进到 X-Window 系统 - # 7. 重新启动 (记得不要把 initdefault 配置为 6,因为这样会使 Linux 不断地重新启动) - printf "\n${CYAN}>>>> 配置 Linux 启动模式${RESET}\n" - sed -i 's/id:5:initdefault:/id:3:initdefault:/' /etc/inittab + # 1. 停机(记得不要把 initdefault 配置为 0,因为这样会使 Linux 不能启动) + # 2. 单用户模式,就像 Win9X 下的安全模式 + # 3. 多用户,但是没有 NFS + # 4. 完全多用户模式,准则的运行级 + # 5. 通常不用,在一些特殊情况下可以用它来做一些事情 + # 6. X11,即进到 X-Window 系统 + # 7. 重新启动 (记得不要把 initdefault 配置为 6,因为这样会使 Linux 不断地重新启动) + printf "\n${CYAN}>>>> 配置 Linux 启动模式${RESET}\n" + sed -i 's/id:5:initdefault:/id:3:initdefault:/' /etc/inittab } # 配置 IPv4 configIpv4() { - printf "\n${CYAN}>>>> 配置 IPv4${RESET}\n" + printf "\n${CYAN}>>>> 配置 IPv4${RESET}\n" -cat >> /etc/sysctl.conf << EOF + cat >> /etc/sysctl.conf << EOF net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 1 net.ipv4.tcp_fin_timeout = 2 @@ -90,14 +90,14 @@ EOF # 关闭 IPv6 closeIpv6() { - printf "\n${CYAN}>>>> 关闭 IPv6${RESET}\n" + printf "\n${CYAN}>>>> 关闭 IPv6${RESET}\n" -cat > /etc/modprobe.d/ipv6.conf << EOF + cat > /etc/modprobe.d/ipv6.conf << EOF alias net-pf-10 off options ipv6 disable=1 EOF - echo "NETWORKING_IPV6=off" >> /etc/sysconfig/network + echo "NETWORKING_IPV6=off" >> /etc/sysconfig/network } # 入口函数 @@ -107,26 +107,26 @@ main() { do case ${ITEM} in - "配置 DNS") - sh ${root}/set-dns.sh ;; - "配置 NTP") - sh ${root}/set-ntp.sh ;; - "关闭防火墙") - sh ${root}/stop-firewall.sh ;; - "配置 IPv4") - configIpv4 ;; - "关闭 IPv6") - closeIpv6 ;; - "全部执行") - sh ${root}/set-dns.sh - sh ${root}/set-ntp.sh - sh ${root}/stop-firewall.sh - configIpv4 - closeIpv6 + "配置 DNS") + sh ${root}/set-dns.sh ;; + "配置 NTP") + sh ${root}/set-ntp.sh ;; + "关闭防火墙") + sh ${root}/stop-firewall.sh ;; + "配置 IPv4") + configIpv4 ;; + "关闭 IPv6") + closeIpv6 ;; + "全部执行") + sh ${root}/set-dns.sh + sh ${root}/set-ntp.sh + sh ${root}/stop-firewall.sh + configIpv4 + closeIpv6 ;; - *) - printf "\n${RED}输入项不支持${RESET}\n" - main + *) + printf "\n${RED}输入项不支持${RESET}\n" + main ;; esac break @@ -136,7 +136,7 @@ main() { ######################################## MAIN ######################################## root=$(pwd) if [[ -n $1 ]]; then - root=$1 + root=$1 fi printHeadInfo diff --git a/codes/linux/sys/syscheck b/codes/linux/sys/syscheck deleted file mode 100644 index 6ced585..0000000 --- a/codes/linux/sys/syscheck +++ /dev/null @@ -1,325 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -# console color -C_RESET="$(tput sgr0)" -C_BLACK="\033[1;30m" -C_RED="\033[1;31m" -C_GREEN="\033[1;32m" -C_YELLOW="\033[1;33m" -C_BLUE="\033[1;34m" -C_PURPLE="\033[1;35m" -C_CYAN="\033[1;36m" -C_WHITE="\033[1;37m" -############################################################################## - -printf "${C_PURPLE}" -cat << EOF - -################################################################################### -# 系统信息检查脚本 -# @author: Zhang Peng -################################################################################### - -EOF -printf "${C_RESET}" - -[[ $(id -u) -gt 0 ]] && echo "请用root用户执行此脚本!" && exit 1 -sysversion=$(rpm -q centos-release|cut -d- -f3) -double_line="===============================================================" -line="----------------------------------------------" - -# 打印头部信息 -printHeadInfo() { -cat << EOF - -+---------------------------------------------------------------------------------+ -| 欢迎使用 【系统信息检查脚本】 | -| @author: Zhang Peng | -+---------------------------------------------------------------------------------+ - -EOF -} - -# 打印尾部信息 -printFootInfo() { -cat << EOF - -+---------------------------------------------------------------------------------+ -| 脚本执行结束,感谢使用! | -+---------------------------------------------------------------------------------+ - -EOF -} - -options=("获取系统信息" "获取服务信息" "获取CPU信息" "获取系统网络信息" "获取系统内存信息" "获取系统磁盘信息" "获取CPU/内存占用TOP10" "获取系统用户信息" "输出所有信息" "退出") -printMenu() { -printf "${C_BLUE}" -printf "主菜单:\n" -for i in "${!options[@]}"; do - index=`expr ${i} + 1` - val=`expr ${index} % 2` - printf "\t(%02d) %-30s" "${index}" "${options[$i]}" - if [[ ${val} -eq 0 ]]; then - printf "\n" - fi -done -printf "${C_BLUE}请输入需要执行的指令:\n" -printf "${C_RESET}" -} - -# 获取系统信息 -get_systatus_info() { - sys_os=$(uname -o) - sys_release=$(cat /etc/redhat-release) - sys_kernel=$(uname -r) - sys_hostname=$(hostname) - sys_selinux=$(getenforce) - sys_lang=$(echo $LANG) - sys_lastreboot=$(who -b | awk '{print $3,$4}') - sys_runtime=$(uptime |awk '{print $3,$4}'|cut -d, -f1) - sys_time=$(date) - sys_load=$(uptime |cut -d: -f5) - -cat << EOF -【系统信息】 - -系统: ${sys_os} -发行版本: ${sys_release} -系统内核: ${sys_kernel} -主机名: ${sys_hostname} -selinux状态: ${sys_selinux} -系统语言: ${sys_lang} -系统当前时间: ${sys_time} -系统最后重启时间: ${sys_lastreboot} -系统运行时间: ${sys_runtime} -系统负载: ${sys_load} -EOF -} - -# 获取CPU信息 -get_cpu_info() { - Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l) - Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l) - CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}') - CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq) - CPU_Arch=$(uname -m) -cat << EOF -【CPU信息】 - -物理CPU个数:$Physical_CPUs -逻辑CPU个数:$Virt_CPUs -每CPU核心数:$CPU_Kernels -CPU型号:$CPU_Type -CPU架构:$CPU_Arch -EOF -} - -# 获取服务信息 -get_service_info() { - port_listen=$(netstat -lntup|grep -v "Active Internet") - kernel_config=$(sysctl -p 2>/dev/null) - if [[ ${sysversion} -gt 6 ]];then - service_config=$(systemctl list-unit-files --type=service --state=enabled|grep "enabled") - run_service=$(systemctl list-units --type=service --state=running |grep ".service") - else - service_config=$(/sbin/chkconfig | grep -E ":on|:启用" |column -t) - run_service=$(/sbin/service --status-all|grep -E "running") - fi -cat << EOF -【服务信息】 - -${service_config} -${line} -运行的服务: - -${run_service} -${line} -监听端口: - -${port_listen} -${line} -内核参考配置: - -${kernel_config} -EOF -} - -# 获取系统内存信息 -get_mem_info() { - check_mem=$(free -m) - MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}') #KB - MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}') #KB - let MemUsed=MemTotal-MemFree - MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}") - report_MemTotal="$((MemTotal/1024))""MB" #内存总容量(MB) - report_MemFree="$((MemFree/1024))""MB" #内存剩余(MB) - report_MemUsedPercent=$(free | sed -n '2p' | gawk 'x = int(( $3 / $2 ) * 100) {print x}' | sed 's/$/%/') - -cat << EOF -【内存信息】 - -内存总容量(MB): ${report_MemTotal} -内存剩余量(MB):${report_MemFree} -内存使用率: ${report_MemUsedPercent} -EOF -} - -# 获取系统网络信息 -get_net_info() { - pri_ipadd=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') - pub_ipadd=$(curl ifconfig.me -s) - gateway=$(ip route | grep default | awk '{print $3}') - mac_info=$(ip link| egrep -v "lo"|grep link|awk '{print $2}') - dns_config=$(egrep -v "^$|^#" /etc/resolv.conf) - route_info=$(route -n) -cat << EOF -【网络信息】 - -系统公网地址:${pub_ipadd} -系统私网地址:${pri_ipadd} -网关地址:${gateway} -MAC地址:${mac_info} - -路由信息: -${route_info} - -DNS 信息: -${dns_config} -EOF -} - -# 获取系统磁盘信息 -get_disk_info() { - disk_info=$(fdisk -l|grep "Disk /dev"|cut -d, -f1) - disk_use=$(df -hTP|awk '$2!="tmpfs"{print}') - disk_percent=$(free | sed -n '2p' | gawk 'x = int(( $3 / $2 ) * 100) {print x}' | sed 's/$/%/') - disk_inode=$(df -hiP|awk '$1!="tmpfs"{print}') - -cat << EOF -【磁盘信息】 - -${disk_info} - -磁盘使用: ${disk_use} -磁盘使用百分比: ${disk_percent} -inode信息: ${disk_inode} -EOF -} - -# 获取系统用户信息 -get_sys_user() { - login_user=$(awk -F: '{if ($NF=="/bin/bash") print $0}' /etc/passwd) - ssh_config=$(egrep -v "^#|^$" /etc/ssh/sshd_config) - sudo_config=$(egrep -v "^#|^$" /etc/sudoers |grep -v "^Defaults") - host_config=$(egrep -v "^#|^$" /etc/hosts) - crond_config=$(for cronuser in /var/spool/cron/* ;do ls ${cronuser} 2>/dev/null|cut -d/ -f5;egrep -v "^$|^#" ${cronuser} 2>/dev/null;echo "";done) -cat << EOF -【用户信息】 - -系统登录用户: - -${login_user} -${line} -ssh 配置信息: - -${ssh_config} -${line} -sudo 配置用户: - -${sudo_config} -${line} -定时任务配置: - -${crond_config} -${line} -hosts 信息: - -${host_config} -EOF -} - -# 获取CPU/内存占用TOP10 -get_process_top_info() { - - top_title=$(top -b n1 | head -7 | tail -1) - cpu_top10=$(top -b n1 | head -17 | tail -11) - mem_top10=$(top -b n1 | head -17 | tail -10 | sort -k10 -r) - -cat << EOF -【TOP10】 -CPU占用TOP10: - -${cpu_top10} - -内存占用TOP10: - -${top_title} -${mem_top10} -EOF -} - -show_dead_process() { - printf "僵尸进程:\n" - ps -al | gawk '{print $2,$4}' | grep Z -} - -get_all_info() { - get_systatus_info - echo ${double_line} - get_service_info - echo ${double_line} - get_cpu_info - echo ${double_line} - get_net_info - echo ${double_line} - get_mem_info - echo ${double_line} - get_disk_info - echo ${double_line} - get_process_top_info - echo ${double_line} - get_sys_user -} - -main() { -while [[ 1 ]] -do - printMenu - read option - local index=$[${option} - 1] - case ${options[${index}]} in - "获取系统信息") - get_systatus_info;; - "获取服务信息") - get_service_info ;; - "获取CPU信息") - get_cpu_info ;; - "获取系统网络信息") - get_net_info ;; - "获取系统内存信息") - get_mem_info ;; - "获取系统磁盘信息") - get_disk_info ;; - "获取CPU/内存占用TOP10") - get_process_top_info ;; - "获取系统用户信息") - get_sys_user ;; - "输出所有信息") - get_all_info > sys.log - printf "${C_GREEN}信息已经输出到 sys.log 中。${C_RESET}\n\n" - ;; - "退出") - exit ;; - *) - clear - echo "抱歉,不支持此选项";; - esac -done -} - -######################################## MAIN ######################################## -printHeadInfo -main -printFootInfo -printf "${C_RESET}" diff --git a/codes/linux/sys/syscheck.sh b/codes/linux/sys/syscheck.sh new file mode 100644 index 0000000..c5ac52a --- /dev/null +++ b/codes/linux/sys/syscheck.sh @@ -0,0 +1,328 @@ +#!/usr/bin/env bash + +############################################################################## +# console color +C_RESET="$(tput sgr0)" +C_BLACK="\033[1;30m" +C_RED="\033[1;31m" +C_GREEN="\033[1;32m" +C_YELLOW="\033[1;33m" +C_BLUE="\033[1;34m" +C_PURPLE="\033[1;35m" +C_CYAN="\033[1;36m" +C_WHITE="\033[1;37m" +############################################################################## + +printf "${C_PURPLE}" +cat << EOF + +################################################################################### +# 系统信息检查脚本 +# @author: Zhang Peng +################################################################################### + +EOF +printf "${C_RESET}" + +[[ $(id -u) -gt 0 ]] && echo "请用root用户执行此脚本!" && exit 1 +sysversion=$(rpm -q centos-release | cut -d- -f3) +double_line="===============================================================" +line="----------------------------------------------" + +# 打印头部信息 +printHeadInfo() { + cat << EOF + ++---------------------------------------------------------------------------------+ +| 欢迎使用 【系统信息检查脚本】 | +| @author: Zhang Peng | ++---------------------------------------------------------------------------------+ + +EOF +} + +# 打印尾部信息 +printFootInfo() { + cat << EOF + ++---------------------------------------------------------------------------------+ +| 脚本执行结束,感谢使用! | ++---------------------------------------------------------------------------------+ + +EOF +} + +options=( "获取系统信息" "获取服务信息" "获取CPU信息" "获取系统网络信息" "获取系统内存信息" "获取系统磁盘信息" "获取CPU/内存占用TOP10" "获取系统用户信息" "输出所有信息" "退出" ) +printMenu() { + printf "${C_BLUE}" + printf "主菜单:\n" + for i in "${!options[@]}"; do + index=`expr ${i} + 1` + val=`expr ${index} % 2` + printf "\t(%02d) %-30s" "${index}" "${options[$i]}" + if [[ ${val} -eq 0 ]]; then + printf "\n" + fi + done + printf "${C_BLUE}请输入需要执行的指令:\n" + printf "${C_RESET}" +} + +# 获取系统信息 +get_systatus_info() { + sys_os=$(uname -o) + sys_release=$(cat /etc/redhat-release) + sys_kernel=$(uname -r) + sys_hostname=$(hostname) + sys_selinux=$(getenforce) + sys_lang=$(echo $LANG) + sys_lastreboot=$(who -b | awk '{print $3,$4}') + sys_runtime=$(uptime | awk '{print $3,$4}' | cut -d, -f1) + sys_time=$(date) + sys_load=$(uptime | cut -d: -f5) + + cat << EOF +【系统信息】 + +系统: ${sys_os} +发行版本: ${sys_release} +系统内核: ${sys_kernel} +主机名: ${sys_hostname} +selinux状态: ${sys_selinux} +系统语言: ${sys_lang} +系统当前时间: ${sys_time} +系统最后重启时间: ${sys_lastreboot} +系统运行时间: ${sys_runtime} +系统负载: ${sys_load} +EOF +} + +# 获取CPU信息 +get_cpu_info() { + Physical_CPUs=$(grep "physical id" /proc/cpuinfo | sort | uniq | wc -l) + Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l) + CPU_Kernels=$(grep "cores" /proc/cpuinfo | uniq | awk -F ': ' '{print $2}') + CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq) + CPU_Arch=$(uname -m) + cat << EOF +【CPU信息】 + +物理CPU个数:$Physical_CPUs +逻辑CPU个数:$Virt_CPUs +每CPU核心数:$CPU_Kernels +CPU型号:$CPU_Type +CPU架构:$CPU_Arch +EOF +} + +# 获取服务信息 +get_service_info() { + port_listen=$(netstat -lntup | grep -v "Active Internet") + kernel_config=$(sysctl -p 2> /dev/null) + if [[ ${sysversion} -gt 6 ]]; then + service_config=$(systemctl list-unit-files --type=service --state=enabled | grep "enabled") + run_service=$(systemctl list-units --type=service --state=running | grep ".service") + else + service_config=$(/sbin/chkconfig | grep -E ":on|:启用" | column -t) + run_service=$(/sbin/service --status-all | grep -E "running") + fi + cat << EOF +【服务信息】 + +${service_config} + ${line} +运行的服务: + +${run_service} + ${line} +监听端口: + +${port_listen} + ${line} +内核参考配置: + +${kernel_config} +EOF +} + +# 获取系统内存信息 +get_mem_info() { + check_mem=$(free -m) + MemTotal=$(grep MemTotal /proc/meminfo | awk '{print $2}') #KB + MemFree=$(grep MemFree /proc/meminfo | awk '{print $2}') #KB + let MemUsed=MemTotal-MemFree + MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}") + report_MemTotal="$((MemTotal/1024))" "MB" #内存总容量(MB) + report_MemFree="$((MemFree/1024))" "MB" #内存剩余(MB) + report_MemUsedPercent=$(free | sed -n '2p' | gawk 'x = int(( $3 / $2 ) * 100) {print x}' | sed 's/$/%/') + + cat << EOF +【内存信息】 + +内存总容量(MB): ${report_MemTotal} +内存剩余量(MB):${report_MemFree} +内存使用率: ${report_MemUsedPercent} +EOF +} + +# 获取系统网络信息 +get_net_info() { + pri_ipadd=$(ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}') + pub_ipadd=$(curl ifconfig.me -s) + gateway=$(ip route | grep default | awk '{print $3}') + mac_info=$(ip link | egrep -v "lo" | grep link | awk '{print $2}') + dns_config=$(egrep -v "^$|^#" /etc/resolv.conf) + route_info=$(route -n) + cat << EOF +【网络信息】 + +系统公网地址:${pub_ipadd} +系统私网地址:${pri_ipadd} +网关地址:${gateway} +MAC地址:${mac_info} + +路由信息: +${route_info} + +DNS 信息: +${dns_config} +EOF +} + +# 获取系统磁盘信息 +get_disk_info() { + disk_info=$(fdisk -l | grep "Disk /dev" | cut -d, -f1) + disk_use=$(df -hTP | awk '$2!="tmpfs"{print}') + disk_percent=$(free | sed -n '2p' | gawk 'x = int(( $3 / $2 ) * 100) {print x}' | sed 's/$/%/') + disk_inode=$(df -hiP | awk '$1!="tmpfs"{print}') + + cat << EOF +【磁盘信息】 + +${disk_info} + +磁盘使用: ${disk_use} +磁盘使用百分比: ${disk_percent} +inode信息: ${disk_inode} +EOF +} + +# 获取系统用户信息 +get_sys_user() { + login_user=$(awk -F: '{if ($NF=="/bin/bash") print $0}' /etc/passwd) + ssh_config=$(egrep -v "^#|^$" /etc/ssh/sshd_config) + sudo_config=$(egrep -v "^#|^$" /etc/sudoers | grep -v "^Defaults") + host_config=$(egrep -v "^#|^$" /etc/hosts) + crond_config=$(for cronuser in /var/spool/cron/*; do + ls ${cronuser} 2> /dev/null | cut -d/ -f5; egrep -v "^$|^#" ${cronuser} 2> /dev/null; + echo ""; + done) + cat << EOF +【用户信息】 + +系统登录用户: + +${login_user} + ${line} +ssh 配置信息: + +${ssh_config} + ${line} +sudo 配置用户: + +${sudo_config} + ${line} +定时任务配置: + +${crond_config} + ${line} +hosts 信息: + +${host_config} +EOF +} + +# 获取CPU/内存占用TOP10 +get_process_top_info() { + + top_title=$(top -b n1 | head -7 | tail -1) + cpu_top10=$(top -b n1 | head -17 | tail -11) + mem_top10=$(top -b n1 | head -17 | tail -10 | sort -k10 -r) + + cat << EOF +【TOP10】 +CPU占用TOP10: + +${cpu_top10} + +内存占用TOP10: + +${top_title} + ${mem_top10} +EOF +} + +show_dead_process() { + printf "僵尸进程:\n" + ps -al | gawk '{print $2,$4}' | grep Z +} + +get_all_info() { + get_systatus_info + echo ${double_line} + get_service_info + echo ${double_line} + get_cpu_info + echo ${double_line} + get_net_info + echo ${double_line} + get_mem_info + echo ${double_line} + get_disk_info + echo ${double_line} + get_process_top_info + echo ${double_line} + get_sys_user +} + +main() { + while [[ 1 ]] + do + printMenu + read option + local index=$[ ${option} - 1 ] + case ${options[${index}]} in + "获取系统信息") + get_systatus_info ;; + "获取服务信息") + get_service_info ;; + "获取CPU信息") + get_cpu_info ;; + "获取系统网络信息") + get_net_info ;; + "获取系统内存信息") + get_mem_info ;; + "获取系统磁盘信息") + get_disk_info ;; + "获取CPU/内存占用TOP10") + get_process_top_info ;; + "获取系统用户信息") + get_sys_user ;; + "输出所有信息") + get_all_info > sys.log + printf "${C_GREEN}信息已经输出到 sys.log 中。${C_RESET}\n\n" + ;; + "退出") + exit ;; + *) + clear + echo "抱歉,不支持此选项" ;; + esac + done +} + +######################################## MAIN ######################################## +printHeadInfo +main +printFootInfo +printf "${C_RESET}" diff --git a/codes/linux/tool/Autoinstall_ELK_V1.3.sh b/codes/linux/tool/Autoinstall_ELK_V1.3.sh index 87557dd..f1ad94e 100644 --- a/codes/linux/tool/Autoinstall_ELK_V1.3.sh +++ b/codes/linux/tool/Autoinstall_ELK_V1.3.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #mail:xuel@anchnet.com #data:2017/9/7 @@ -23,29 +23,29 @@ sys_mem=`free -m | grep Mem: | awk '{print $2}' | awk '{sum+=$1} END {print sum/ #wget software wget_fun() { - if [ ! -d ${software_dir} ]; then - mkdir -p ${software_dir} && cd ${software_dir} - else - cd ${software_dir} - fi - for software in $elasticsearch_url $kibana_url $logstash_url $filebeat_url - do - wget -c $software - done - clear + if [ ! -d ${software_dir} ]; then + mkdir -p ${software_dir} && cd ${software_dir} + else + cd ${software_dir} + fi + for software in $elasticsearch_url $kibana_url $logstash_url $filebeat_url + do + wget -c $software + done + clear } #initial system:install java wget;set hostname;disable firewalld init_sys() { - [ -f /etc/init.d/functions ] && . /etc/init.d/functions - [ "${sys_version}" != "7" ] && echo "Error:This Scripts Support Centos7.xx" && exit 1 - [ $(id -u) != "0" ] && echo "Error: You must be root to run this script" && exit 1 - sed -i "s/SELINUX=enforcing/SELINUX=disabled/" /etc/selinux/config - setenforce 0 - yum install -y java-1.8.0-openjdk wget net-tools - hostnamectl set-hostname elk-server - systemctl stop firewalld - cat >> /etc/security/limits.conf << EOF + [ -f /etc/init.d/functions ] && . /etc/init.d/functions + [ "${sys_version}" != "7" ] && echo "Error:This Scripts Support Centos7.xx" && exit 1 + [ $(id -u) != "0" ] && echo "Error: You must be root to run this script" && exit 1 + sed -i "s/SELINUX=enforcing/SELINUX=disabled/" /etc/selinux/config + setenforce 0 + yum install -y java-1.8.0-openjdk wget net-tools + hostnamectl set-hostname elk-server + systemctl stop firewalld + cat >> /etc/security/limits.conf << EOF * soft nofile 65536 * hard nofile 65536 * soft nGproc 65536 @@ -55,21 +55,21 @@ EOF #install elasticsearch install_elasticsearch() { - cd $software_dir - tar zxf elasticsearch-5.4.1.tar.gz - mv elasticsearch-5.4.1 /usr/local/elasticsearch - mkdir -p /usr/local/elasticsearch/data /usr/local/elasticsearch/logs - useradd elasticsearch - chown -R elasticsearch:elasticsearch /usr/local/elasticsearch - echo "vm.max_map_count = 655360" >> /etc/sysctl.conf && sysctl -p - if [ ${sys_mem} -eq 0 ]; then - sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx512m"#g" ${jvm_conf} - sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms512m"#g" ${jvm_conf} - else - sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx${sys_mem}g"#g" ${jvm_conf} - sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms${sys_mem}g"#g" ${jvm_conf} - fi - cat >> /usr/local/elasticsearch/config/elasticsearch.yml << EOF + cd $software_dir + tar zxf elasticsearch-5.4.1.tar.gz + mv elasticsearch-5.4.1 /usr/local/elasticsearch + mkdir -p /usr/local/elasticsearch/data /usr/local/elasticsearch/logs + useradd elasticsearch + chown -R elasticsearch:elasticsearch /usr/local/elasticsearch + echo "vm.max_map_count = 655360" >> /etc/sysctl.conf && sysctl -p + if [ ${sys_mem} -eq 0 ]; then + sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx512m"#g" ${jvm_conf} + sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms512m"#g" ${jvm_conf} + else + sed -i "s#`grep "^-Xmx" ${jvm_conf}`#"-Xmx${sys_mem}g"#g" ${jvm_conf} + sed -i "s#`grep "^-Xms" ${jvm_conf}`#"-Xms${sys_mem}g"#g" ${jvm_conf} + fi + cat >> /usr/local/elasticsearch/config/elasticsearch.yml << EOF cluster.name: my-application node.name: elk-server path.data: /usr/local/elasticsearch/data @@ -78,15 +78,15 @@ network.host: 127.0.0.1 http.port: 9200 discovery.zen.ping.unicast.hosts: ["elk-server"] EOF - su - elasticsearch -c "nohup /usr/local/elasticsearch/bin/elasticsearch &" + su - elasticsearch -c "nohup /usr/local/elasticsearch/bin/elasticsearch &" } #install logstash install_logstash() { - cd $software_dir - tar -zxf logstash-5.4.1.tar.gz - mv logstash-5.4.1 /usr/local/logstash - cat > /usr/local/logstash/config/01-syslog.conf << EOF + cd $software_dir + tar -zxf logstash-5.4.1.tar.gz + mv logstash-5.4.1 /usr/local/logstash + cat > /usr/local/logstash/config/01-syslog.conf << EOF input { beats { port => "5044" @@ -99,15 +99,15 @@ output { stdout { codec => rubydebug } } EOF - nohup /usr/local/logstash/bin/logstash -f /usr/local/logstash/config/01-syslog.conf & > /dev/null + nohup /usr/local/logstash/bin/logstash -f /usr/local/logstash/config/01-syslog.conf & > /dev/null } #install filebeat install_filebeat() { - cd $software_dir - tar -zxf filebeat-5.4.1-linux-x86_64.tar.gz - mv filebeat-5.4.1-linux-x86_64 /usr/local/filebeat - cat > /usr/local/filebeat/filebeat.yml << EOF + cd $software_dir + tar -zxf filebeat-5.4.1-linux-x86_64.tar.gz + mv filebeat-5.4.1-linux-x86_64 /usr/local/filebeat + cat > /usr/local/filebeat/filebeat.yml << EOF filebeat.prospectors: - input_type: log paths: @@ -115,53 +115,53 @@ filebeat.prospectors: output.logstash: hosts: ["127.0.0.1:5044"] EOF - cd /usr/local/filebeat/ - nohup /usr/local/filebeat/filebeat & > /dev/null + cd /usr/local/filebeat/ + nohup /usr/local/filebeat/filebeat & > /dev/null } #install kibana install_kibana() { - cd $software_dir - tar -zxf kibana-5.4.1-linux-x86_64.tar.gz - mv kibana-5.4.1-linux-x86_64 /usr/local/kibana - cat >> /usr/local/kibana/config/kibana.yml << EOF + cd $software_dir + tar -zxf kibana-5.4.1-linux-x86_64.tar.gz + mv kibana-5.4.1-linux-x86_64 /usr/local/kibana + cat >> /usr/local/kibana/config/kibana.yml << EOF server.port: 5601 server.host: "0.0.0.0" elasticsearch.url: "http://127.0.0.1:9200" EOF - nohup /usr/local/kibana/bin/kibana & > /dev/null + nohup /usr/local/kibana/bin/kibana & > /dev/null } check() { - port=$1 - program=$2 - check_port=`netstat -lntup | grep ${port} | wc -l` - check_program=`ps -ef | grep ${program} | grep -v grep | wc -l` - if [ $check_port -gt 0 ] && [ $check_program -gt 0 ]; then - action "${program} run is ok!" /bin/true - else - action "${program} run is error!" /bin/false - fi + port=$1 + program=$2 + check_port=`netstat -lntup | grep ${port} | wc -l` + check_program=`ps -ef | grep ${program} | grep -v grep | wc -l` + if [ $check_port -gt 0 ] && [ $check_program -gt 0 ]; then + action "${program} run is ok!" /bin/true + else + action "${program} run is error!" /bin/false + fi } main() { - init_sys - wget_fun - install_elasticsearch - install_filebeat - install_logstash - install_kibana - echo -e "\033[32m Checking Elasticsearch...\033[0m" - sleep 20 - check :9200 "elasticsearch" - echo -e "\033[32m Checking Logstash...\033[0m" - sleep 2 - check ":9600" "logstash" - echo -e "\033[32m Checking Kibana...\033[0m" - sleep 2 - check ":5601" "kibana" - action "ELK install is success!" /bin/true - echo "url:http://$IP:5601" + init_sys + wget_fun + install_elasticsearch + install_filebeat + install_logstash + install_kibana + echo -e "\033[32m Checking Elasticsearch...\033[0m" + sleep 20 + check :9200 "elasticsearch" + echo -e "\033[32m Checking Logstash...\033[0m" + sleep 2 + check ":9600" "logstash" + echo -e "\033[32m Checking Kibana...\033[0m" + sleep 2 + check ":5601" "kibana" + action "ELK install is success!" /bin/true + echo "url:http://$IP:5601" } main diff --git a/codes/linux/tool/Cpu_Limit.sh b/codes/linux/tool/Cpu_Limit.sh index 5e082e0..2cfa6de 100644 --- a/codes/linux/tool/Cpu_Limit.sh +++ b/codes/linux/tool/Cpu_Limit.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # auth:kaliarch # func:sys info check @@ -21,34 +21,34 @@ PIDARG=$(ps -aux | awk -v CPU=${PEC_CPU} '{if($3 > CPU) print $2}') CPULIMITCMD=$(which cpulimit) install_cpulimit() { - [ ! -d /tmp ] && mkdir /tmp || cd /tmp - wget -c https://github.com/opsengine/cpulimit/archive/v0.2.tar.gz - tar -zxf v0.2.tar.gz - cd cpulimit-0.2 && make - [ $? -eq 0 ] && cp src/cpulimit /usr/bin/ + [ ! -d /tmp ] && mkdir /tmp || cd /tmp + wget -c https://github.com/opsengine/cpulimit/archive/v0.2.tar.gz + tar -zxf v0.2.tar.gz + cd cpulimit-0.2 && make + [ $? -eq 0 ] && cp src/cpulimit /usr/bin/ } do_cpulimit() { - [ ! -d ${LOG_DIR} ] && mkdir -p ${LOG_DIR} - for i in ${PIDARG}; - do - MSG=$(ps -aux | awk -v pid=$i '{if($2 == pid) print $0}') - echo ${MSG} - [ ! -d /tmp ] && mkdir /tmp || cd /tmp - nohup ${CPULIMITCMD} -p $i -l ${LIMIT_CPU} & - echo "$(date) -- ${MSG}" >> ${LOG_DIR}$(date +%F).log - done + [ ! -d ${LOG_DIR} ] && mkdir -p ${LOG_DIR} + for i in ${PIDARG}; + do + MSG=$(ps -aux | awk -v pid=$i '{if($2 == pid) print $0}') + echo ${MSG} + [ ! -d /tmp ] && mkdir /tmp || cd /tmp + nohup ${CPULIMITCMD} -p $i -l ${LIMIT_CPU} & + echo "$(date) -- ${MSG}" >> ${LOG_DIR}$(date +%F).log + done } main() { - hash cpulimit - if [ $? -eq 0 ]; then - do_cpulimit - else - install_cpulimit && do_cpulimit - fi + hash cpulimit + if [ $? -eq 0 ]; then + do_cpulimit + else + install_cpulimit && do_cpulimit + fi } main diff --git a/codes/linux/tool/Custom_Rm.sh b/codes/linux/tool/Custom_Rm.sh index 8b948ee..be19d78 100644 --- a/codes/linux/tool/Custom_Rm.sh +++ b/codes/linux/tool/Custom_Rm.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # function:自定义rm命令,每天晚上定时清理 diff --git a/codes/linux/tool/Daily_Archive.sh b/codes/linux/tool/Daily_Archive.sh index 9fbaafe..3d2e7c4 100644 --- a/codes/linux/tool/Daily_Archive.sh +++ b/codes/linux/tool/Daily_Archive.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Daily_Archive - Archive designated files & directories @@ -23,13 +23,13 @@ DESTINATION=/home/tiandi/archive/$FILE # if [ -f $CONFIG_FILE ] #Make sure the config file still exists then - echo + echo else - echo - echo "$CONFIG_FILE does not exist." - echo "Backup not completed due to missing Configuration file" - echo - exit + echo + echo "$CONFIG_FILE does not exist." + echo "Backup not completed due to missing Configuration file" + echo + exit fi # # Build the names of all the files to backup @@ -41,23 +41,23 @@ read FILE_NAME # Read 1st record # while [ $? -eq 0 ] do - # Make sure the file or directory exists. - if [ -f $FILE_NAME -o -d $FILE_NAME ] - then - # If file exists, add its name to the lists - FILE_LIST="$FILE_LIST $FILE_NAME" - else - # If file doesn't exist, issue warning - echo - echo "$FILE_NAME, does not exist." - echo "Obviously, I will not include it in this archive." - echo "It is listed on line $FILE_NO of the config file." - echo "Continuing to build archive file." - echo - fi - # - FILE_NO=$[ $FILE_NO + 1 ] # Increase Line/File number by one - read FILE_NAME # Read next record. + # Make sure the file or directory exists. + if [ -f $FILE_NAME -o -d $FILE_NAME ] + then + # If file exists, add its name to the lists + FILE_LIST="$FILE_LIST $FILE_NAME" + else + # If file doesn't exist, issue warning + echo + echo "$FILE_NAME, does not exist." + echo "Obviously, I will not include it in this archive." + echo "It is listed on line $FILE_NO of the config file." + echo "Continuing to build archive file." + echo + fi + # + FILE_NO=$[ $FILE_NO + 1 ] # Increase Line/File number by one + read FILE_NAME # Read next record. done ########################################################### # diff --git a/codes/linux/tool/Hourly_Archive.sh b/codes/linux/tool/Hourly_Archive.sh index d29a08e..3220fcf 100644 --- a/codes/linux/tool/Hourly_Archive.sh +++ b/codes/linux/tool/Hourly_Archive.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Hourly_Archive - Every hour create an archive @@ -30,13 +30,13 @@ DESTINATION=$BASEDEST/$MONTH/$DAY/archive$TIME.tar.gz # if [ -f $CONFIG_FILE ] #Make sure the config file still exists then - echo + echo else - echo - echo "$CONFIG_FILE does not exist." - echo "Backup not completed due to missing Configuration file" - echo - exit + echo + echo "$CONFIG_FILE does not exist." + echo "Backup not completed due to missing Configuration file" + echo + exit fi # # Build the names of all the files to backup @@ -48,23 +48,23 @@ read FILE_NAME # Read 1st record # while [ $? -eq 0 ] do - # Make sure the file or directory exists. - if [ -f $FILE_NAME -o -d $FILE_NAME ] - then - # If file exists, add its name to the lists - FILE_LIST="$FILE_LIST $FILE_NAME" - else - # If file doesn't exist, issue warning - echo - echo "$FILE_NAME, does not exist." - echo "Obviously, I will not include it in this archive." - echo "It is listed on line $FILE_NO of the config file." - echo "Continuing to build archive file." - echo - fi - # - FILE_NO=$[ $FILE_NO + 1 ] # Increase Line/File number by one - read FILE_NAME # Read next record. + # Make sure the file or directory exists. + if [ -f $FILE_NAME -o -d $FILE_NAME ] + then + # If file exists, add its name to the lists + FILE_LIST="$FILE_LIST $FILE_NAME" + else + # If file doesn't exist, issue warning + echo + echo "$FILE_NAME, does not exist." + echo "Obviously, I will not include it in this archive." + echo "It is listed on line $FILE_NO of the config file." + echo "Continuing to build archive file." + echo + fi + # + FILE_NO=$[ $FILE_NO + 1 ] # Increase Line/File number by one + read FILE_NAME # Read next record. done ########################################################### # diff --git a/codes/linux/tool/gitcheck b/codes/linux/tool/gitcheck index c650199..3f21766 100644 --- a/codes/linux/tool/gitcheck +++ b/codes/linux/tool/gitcheck @@ -8,14 +8,14 @@ # MIT license if [ -t 1 ]; then - # Our output is not being redirected, so we can use colors. - C_RED="\033[1;31m" - C_GREEN="\033[1;32m" - C_YELLOW="\033[1;33m" - C_BLUE="\033[1;34m" - C_PURPLE="\033[1;35m" - C_CYAN="\033[1;36m" - C_RESET="$(tput sgr0)" + # Our output is not being redirected, so we can use colors. + C_RED="\033[1;31m" + C_GREEN="\033[1;32m" + C_YELLOW="\033[1;33m" + C_BLUE="\033[1;34m" + C_PURPLE="\033[1;35m" + C_CYAN="\033[1;36m" + C_RESET="$(tput sgr0)" fi C_OK="$C_GREEN" @@ -29,8 +29,8 @@ C_STASHES="$C_YELLOW" DEBUG=0 -usage () { - cat << EOF >&2 +usage() { + cat << EOF >&2 Usage: $0 [-w] [-e] [-f] [--no-X] [DIR] [DEPTH=2] @@ -64,183 +64,185 @@ NO_UNTRACKED=0 NO_STASHES=0 while [ \! -z "$1" ]; do - # Stop reading when we've run out of options. - [ "$(echo "$1" | cut -c 1)" != "-" ] && break + # Stop reading when we've run out of options. + [ "$(echo "$1" | cut -c 1)" != "-" ] && break - if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then - usage - exit 1 - fi - if [ "$1" = "-w" ]; then - WARN_NOT_REPO=1 - fi - if [ "$1" = "-e" ]; then - EXCLUDE_OK=1 - fi - if [ "$1" = "-f" ]; then - DO_FETCH=1 - fi - if [ "$1" = "--no-push" ]; then - NO_PUSH=1 - fi - if [ "$1" = "--no-pull" ]; then - NO_PULL=1 - fi - if [ "$1" = "--no-upstream" ]; then - NO_UPSTREAM=1 - fi - if [ "$1" = "--no-uncommitted" ]; then - NO_UNCOMMITTED=1 - fi - if [ "$1" = "--no-untracked" ]; then - NO_UNTRACKED=1 - fi - if [ "$1" = "--no-stashes" ]; then - NO_STASHES=1 - fi + if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then + usage + exit 1 + fi + if [ "$1" = "-w" ]; then + WARN_NOT_REPO=1 + fi + if [ "$1" = "-e" ]; then + EXCLUDE_OK=1 + fi + if [ "$1" = "-f" ]; then + DO_FETCH=1 + fi + if [ "$1" = "--no-push" ]; then + NO_PUSH=1 + fi + if [ "$1" = "--no-pull" ]; then + NO_PULL=1 + fi + if [ "$1" = "--no-upstream" ]; then + NO_UPSTREAM=1 + fi + if [ "$1" = "--no-uncommitted" ]; then + NO_UNCOMMITTED=1 + fi + if [ "$1" = "--no-untracked" ]; then + NO_UNTRACKED=1 + fi + if [ "$1" = "--no-stashes" ]; then + NO_STASHES=1 + fi - shift + shift done if [ -z "$1" ]; then - ROOT_DIR="." + ROOT_DIR="." else - ROOT_DIR="$1" + ROOT_DIR="$1" fi if [ -z "$2" ]; then - DEPTH=2 + DEPTH=2 else - DEPTH="$2" + DEPTH="$2" fi # Find all .git dirs, up to DEPTH levels deep find -L "$ROOT_DIR" -maxdepth "$DEPTH" -type d | while read -r PROJ_DIR do - GIT_DIR="$PROJ_DIR/.git" + GIT_DIR="$PROJ_DIR/.git" - # If this dir is not a repo, and WARN_NOT_REPO is 1, tell the user. - if [ \! -d "$GIT_DIR" ]; then - if [ "$WARN_NOT_REPO" -eq 1 ] && [ "$PROJ_DIR" != "." ]; then - printf "${PROJ_DIR}: not a git repo\n" - fi - continue - fi + # If this dir is not a repo, and WARN_NOT_REPO is 1, tell the user. + if [ \! -d "$GIT_DIR" ]; then + if [ "$WARN_NOT_REPO" -eq 1 ] && [ "$PROJ_DIR" != "." ]; then + printf "${PROJ_DIR}: not a git repo\n" + fi + continue + fi - [ $DEBUG -eq 1 ] && echo "${PROJ_DIR}" + [ $DEBUG -eq 1 ] && echo "${PROJ_DIR}" - # Check if repo is locked - if [ -f "$GIT_DIR/index.lock" ]; then - printf "${PROJ_DIR}: ${C_LOCKED}Locked. Skipping.${C_RESET}\n" - continue - fi + # Check if repo is locked + if [ -f "$GIT_DIR/index.lock" ]; then + printf "${PROJ_DIR}: ${C_LOCKED}Locked. Skipping.${C_RESET}\n" + continue + fi - # Do a 'git fetch' if requested - if [ "$DO_FETCH" -eq 1 ]; then - git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" fetch -q >/dev/null - fi + # Do a 'git fetch' if requested + if [ "$DO_FETCH" -eq 1 ]; then + git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" fetch -q > /dev/null + fi - # Refresh the index, or we might get wrong results. - git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" update-index -q --refresh >/dev/null 2>&1 + # Refresh the index, or we might get wrong results. + git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" update-index -q --refresh > /dev/null 2>&1 - # Find all remote branches that have been checked out and figure out if - # they need a push or pull. We do this with various tests and put the name - # of the branches in NEEDS_XXXX, seperated by newlines. After we're done, - # we remove duplicates from NEEDS_XXX. - NEEDS_PUSH_BRANCHES="" - NEEDS_PULL_BRANCHES="" - NEEDS_UPSTREAM_BRANCHES="" + # Find all remote branches that have been checked out and figure out if + # they need a push or pull. We do this with various tests and put the name + # of the branches in NEEDS_XXXX, seperated by newlines. After we're done, + # we remove duplicates from NEEDS_XXX. + NEEDS_PUSH_BRANCHES="" + NEEDS_PULL_BRANCHES="" + NEEDS_UPSTREAM_BRANCHES="" - for REF_HEAD in $(cd "$GIT_DIR/refs/heads" && find . -type 'f' | sed "s/^\.\///"); do - # Check if this branch is tracking an upstream (local/remote branch) - UPSTREAM=$(git --git-dir "$GIT_DIR" rev-parse --abbrev-ref --symbolic-full-name "$REF_HEAD@{u}" 2>/dev/null) - EXIT_CODE="$?" - if [ "$EXIT_CODE" -eq 0 ]; then - # Branch is tracking a remote branch. Find out how much behind / - # ahead it is of that remote branch. - CNT_AHEAD_BEHIND=$(git --git-dir "$GIT_DIR" rev-list --left-right --count "$REF_HEAD...$UPSTREAM") - CNT_AHEAD=$(echo "$CNT_AHEAD_BEHIND" | awk '{ print $1 }') - CNT_BEHIND=$(echo "$CNT_AHEAD_BEHIND" | awk '{ print $2 }') + for REF_HEAD in $(cd "$GIT_DIR/refs/heads" && find . -type 'f' | sed "s/^\.\///"); do + # Check if this branch is tracking an upstream (local/remote branch) + UPSTREAM=$(git --git-dir "$GIT_DIR" rev-parse --abbrev-ref --symbolic-full-name "$REF_HEAD@{u}" 2> /dev/null) + EXIT_CODE="$?" + if [ "$EXIT_CODE" -eq 0 ]; then + # Branch is tracking a remote branch. Find out how much behind / + # ahead it is of that remote branch. + CNT_AHEAD_BEHIND=$(git --git-dir "$GIT_DIR" rev-list --left-right --count "$REF_HEAD...$UPSTREAM") + CNT_AHEAD=$(echo "$CNT_AHEAD_BEHIND" | awk '{ print $1 }') + CNT_BEHIND=$(echo "$CNT_AHEAD_BEHIND" | awk '{ print $2 }') - [ $DEBUG -eq 1 ] && echo "CNT_AHEAD_BEHIND: $CNT_AHEAD_BEHIND" - [ $DEBUG -eq 1 ] && echo "CNT_AHEAD: $CNT_AHEAD" - [ $DEBUG -eq 1 ] && echo "CNT_BEHIND: $CNT_BEHIND" + [ $DEBUG -eq 1 ] && echo "CNT_AHEAD_BEHIND: $CNT_AHEAD_BEHIND" + [ $DEBUG -eq 1 ] && echo "CNT_AHEAD: $CNT_AHEAD" + [ $DEBUG -eq 1 ] && echo "CNT_BEHIND: $CNT_BEHIND" - if [ "$CNT_AHEAD" -gt 0 ]; then - NEEDS_PUSH_BRANCHES="${NEEDS_PUSH_BRANCHES}\n$REF_HEAD" - fi - if [ "$CNT_BEHIND" -gt 0 ]; then - NEEDS_PULL_BRANCHES="${NEEDS_PULL_BRANCHES}\n$REF_HEAD" - fi + if [ "$CNT_AHEAD" -gt 0 ]; then + NEEDS_PUSH_BRANCHES="${NEEDS_PUSH_BRANCHES}\n$REF_HEAD" + fi + if [ "$CNT_BEHIND" -gt 0 ]; then + NEEDS_PULL_BRANCHES="${NEEDS_PULL_BRANCHES}\n$REF_HEAD" + fi - # Check if this branch is a branch off another branch. and if it needs - # to be updated. - REV_LOCAL=$(git --git-dir "$GIT_DIR" rev-parse --verify "$REF_HEAD" 2>/dev/null) - REV_REMOTE=$(git --git-dir "$GIT_DIR" rev-parse --verify "$UPSTREAM" 2>/dev/null) - REV_BASE=$(git --git-dir "$GIT_DIR" merge-base "$REF_HEAD" "$UPSTREAM" 2>/dev/null) + # Check if this branch is a branch off another branch. and if it needs + # to be updated. + REV_LOCAL=$(git --git-dir "$GIT_DIR" rev-parse --verify "$REF_HEAD" 2> /dev/null) + REV_REMOTE=$(git --git-dir "$GIT_DIR" rev-parse --verify "$UPSTREAM" 2> /dev/null) + REV_BASE=$(git --git-dir "$GIT_DIR" merge-base "$REF_HEAD" "$UPSTREAM" 2> /dev/null) - [ $DEBUG -eq 1 ] && echo "REV_LOCAL: $REV_LOCAL" - [ $DEBUG -eq 1 ] && echo "REV_REMOTE: $REV_REMOTE" - [ $DEBUG -eq 1 ] && echo "REV_BASE: $REV_BASE" + [ $DEBUG -eq 1 ] && echo "REV_LOCAL: $REV_LOCAL" + [ $DEBUG -eq 1 ] && echo "REV_REMOTE: $REV_REMOTE" + [ $DEBUG -eq 1 ] && echo "REV_BASE: $REV_BASE" - if [ "$REV_LOCAL" = "$REV_REMOTE" ]; then - : # NOOP - else - if [ "$REV_LOCAL" = "$REV_BASE" ]; then - NEEDS_PULL_BRANCHES="${NEEDS_PULL_BRANCHES}\n$REF_HEAD" - fi - if [ "$REV_REMOTE" = "$REV_BASE" ]; then - NEEDS_PUSH_BRANCHES="${NEEDS_PUSH_BRANCHES}\n$REF_HEAD" - fi - fi - else - # Branch does not have an upstream (local/remote branch). - NEEDS_UPSTREAM_BRANCHES="${NEEDS_UPSTREAM_BRANCHES}\n$REF_HEAD" - fi + if [ "$REV_LOCAL" = "$REV_REMOTE" ]; then + : # NOOP + else + if [ "$REV_LOCAL" = "$REV_BASE" ]; then + NEEDS_PULL_BRANCHES="${NEEDS_PULL_BRANCHES}\n$REF_HEAD" + fi + if [ "$REV_REMOTE" = "$REV_BASE" ]; then + NEEDS_PUSH_BRANCHES="${NEEDS_PUSH_BRANCHES}\n$REF_HEAD" + fi + fi + else + # Branch does not have an upstream (local/remote branch). + NEEDS_UPSTREAM_BRANCHES="${NEEDS_UPSTREAM_BRANCHES}\n$REF_HEAD" + fi - done + done - # Remove duplicates from NEEDS_XXXX and make comma-seperated - NEEDS_PUSH_BRANCHES=$(printf "$NEEDS_PUSH_BRANCHES" | sort | uniq | tr '\n' ',' | sed "s/^,\(.*\),$/\1/") - NEEDS_PULL_BRANCHES=$(printf "$NEEDS_PULL_BRANCHES" | sort | uniq | tr '\n' ',' | sed "s/^,\(.*\),$/\1/") - NEEDS_UPSTREAM_BRANCHES=$(printf "$NEEDS_UPSTREAM_BRANCHES" | sort | uniq | tr '\n' ',' | sed "s/^,\(.*\),$/\1/") + # Remove duplicates from NEEDS_XXXX and make comma-seperated + NEEDS_PUSH_BRANCHES=$(printf "$NEEDS_PUSH_BRANCHES" | sort | uniq | tr '\n' ',' | sed "s/^,\(.*\),$/\1/") + NEEDS_PULL_BRANCHES=$(printf "$NEEDS_PULL_BRANCHES" | sort | uniq | tr '\n' ',' | sed "s/^,\(.*\),$/\1/") + NEEDS_UPSTREAM_BRANCHES=$(printf "$NEEDS_UPSTREAM_BRANCHES" | sort | uniq | tr '\n' ',' | sed "s/^,\(.*\),$/\1/") - # Find out if there are unstaged, uncommitted or untracked changes - UNSTAGED=$(git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" diff-index --quiet HEAD -- 2>/dev/null; echo $?) - UNCOMMITTED=$(git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" diff-files --quiet --ignore-submodules --; echo $?) - UNTRACKED=$(git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" ls-files --exclude-standard --others) - cd "$(dirname "$GIT_DIR")" || exit - STASHES=$(git stash list | wc -l) - cd "$OLDPWD" || exit + # Find out if there are unstaged, uncommitted or untracked changes + UNSTAGED=$(git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" diff-index --quiet HEAD -- 2> /dev/null; + echo $?) + UNCOMMITTED=$(git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" diff-files --quiet --ignore-submodules --; + echo $?) + UNTRACKED=$(git --work-tree "$(dirname "$GIT_DIR")" --git-dir "$GIT_DIR" ls-files --exclude-standard --others) + cd "$(dirname "$GIT_DIR")" || exit + STASHES=$(git stash list | wc -l) + cd "$OLDPWD" || exit - # Build up the status string - IS_OK=0 # 0 = Repo needs something, 1 = Repo needs nothing ('ok') - STATUS_NEEDS="" - if [ \! -z "$NEEDS_PUSH_BRANCHES" ] && [ "$NO_PUSH" -eq 0 ]; then - STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_PUSH}Needs push ($NEEDS_PUSH_BRANCHES)${C_RESET} " - fi - if [ \! -z "$NEEDS_PULL_BRANCHES" ] && [ "$NO_PULL" -eq 0 ]; then - STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_PULL}Needs pull ($NEEDS_PULL_BRANCHES)${C_RESET} " - fi - if [ \! -z "$NEEDS_UPSTREAM_BRANCHES" ] && [ "$NO_UPSTREAM" -eq 0 ]; then - STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_UPSTREAM}Needs upstream ($NEEDS_UPSTREAM_BRANCHES)${C_RESET} " - fi - if [ "$UNSTAGED" -ne 0 ] || [ "$UNCOMMITTED" -ne 0 ] && [ "$NO_UNCOMMITTED" -eq 0 ]; then - STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_COMMIT}Uncommitted changes${C_RESET} " - fi - if [ "$UNTRACKED" != "" ] && [ "$NO_UNTRACKED" -eq 0 ]; then - STATUS_NEEDS="${STATUS_NEEDS}${C_UNTRACKED}Untracked files${C_RESET} " - fi - if [ "$STASHES" -ne 0 ] && [ "$NO_STASHES" -eq 0 ]; then - STATUS_NEEDS="${STATUS_NEEDS}${C_STASHES}$STASHES stashes${C_RESET} " - fi - if [ "$STATUS_NEEDS" = "" ]; then - IS_OK=1 - STATUS_NEEDS="${STATUS_NEEDS}${C_OK}ok${C_RESET} " - fi + # Build up the status string + IS_OK=0 # 0 = Repo needs something, 1 = Repo needs nothing ('ok') + STATUS_NEEDS="" + if [ \! -z "$NEEDS_PUSH_BRANCHES" ] && [ "$NO_PUSH" -eq 0 ]; then + STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_PUSH}Needs push ($NEEDS_PUSH_BRANCHES)${C_RESET} " + fi + if [ \! -z "$NEEDS_PULL_BRANCHES" ] && [ "$NO_PULL" -eq 0 ]; then + STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_PULL}Needs pull ($NEEDS_PULL_BRANCHES)${C_RESET} " + fi + if [ \! -z "$NEEDS_UPSTREAM_BRANCHES" ] && [ "$NO_UPSTREAM" -eq 0 ]; then + STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_UPSTREAM}Needs upstream ($NEEDS_UPSTREAM_BRANCHES)${C_RESET} " + fi + if [ "$UNSTAGED" -ne 0 ] || [ "$UNCOMMITTED" -ne 0 ] && [ "$NO_UNCOMMITTED" -eq 0 ]; then + STATUS_NEEDS="${STATUS_NEEDS}${C_NEEDS_COMMIT}Uncommitted changes${C_RESET} " + fi + if [ "$UNTRACKED" != "" ] && [ "$NO_UNTRACKED" -eq 0 ]; then + STATUS_NEEDS="${STATUS_NEEDS}${C_UNTRACKED}Untracked files${C_RESET} " + fi + if [ "$STASHES" -ne 0 ] && [ "$NO_STASHES" -eq 0 ]; then + STATUS_NEEDS="${STATUS_NEEDS}${C_STASHES}$STASHES stashes${C_RESET} " + fi + if [ "$STATUS_NEEDS" = "" ]; then + IS_OK=1 + STATUS_NEEDS="${STATUS_NEEDS}${C_OK}ok${C_RESET} " + fi - # Print the output, unless repo is 'ok' and -e was specified - if [ "$IS_OK" -ne 1 ] || [ "$EXCLUDE_OK" -ne 1 ]; then - printf "${PROJ_DIR}: $STATUS_NEEDS\n" - fi + # Print the output, unless repo is 'ok' and -e was specified + if [ "$IS_OK" -ne 1 ] || [ "$EXCLUDE_OK" -ne 1 ]; then + printf "${PROJ_DIR}: $STATUS_NEEDS\n" + fi done diff --git a/codes/linux/tool/删除用户脚本.sh b/codes/linux/tool/删除用户脚本.sh index 2da94f7..a7db930 100644 --- a/codes/linux/tool/删除用户脚本.sh +++ b/codes/linux/tool/删除用户脚本.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Delete_User - Automates the 4 steps to remove an account @@ -9,81 +9,81 @@ # ################################################################# function get_answer { - # - unset ANSWER - ASK_COUNT=0 - # - while [ -z "$ANSWER" ] # while no answer is given, keep asking - do - ASK_COUNT=$[ $ASK_COUNT + 1 ] - # - case $ASK_COUNT in - # If user gives no answer in time allowed - 2) - echo - echo "Please answer the question." - echo - ;; - 3) - echo - echo "One last try... please answer the question." - echo - ;; - 4) - echo - echo "Since you refuse to answer the question..." - echo "exiting program." - echo - # - exit - ;; - esac - # - echo - # - if [ -n "$LINE2" ] - then - echo $LINE1 # Print 2 lines - echo -e $LINE2" \c" - else - # Print 1 line - echo -e $LINE1" \c" - fi - # - # Allow 60 seconds to answer before time-out - read -t 60 ANSWER - done - # - # Do a little variable clean-up - # - unset LINE1 - unset LINE2 - # + # + unset ANSWER + ASK_COUNT=0 + # + while [ -z "$ANSWER" ] # while no answer is given, keep asking + do + ASK_COUNT=$[ $ASK_COUNT + 1 ] + # + case $ASK_COUNT in + # If user gives no answer in time allowed + 2) + echo + echo "Please answer the question." + echo + ;; + 3) + echo + echo "One last try... please answer the question." + echo + ;; + 4) + echo + echo "Since you refuse to answer the question..." + echo "exiting program." + echo + # + exit + ;; + esac + # + echo + # + if [ -n "$LINE2" ] + then + echo $LINE1 # Print 2 lines + echo -e $LINE2" \c" + else + # Print 1 line + echo -e $LINE1" \c" + fi + # + # Allow 60 seconds to answer before time-out + read -t 60 ANSWER + done + # + # Do a little variable clean-up + # + unset LINE1 + unset LINE2 + # } #end of get_answer function # ################################################################# function process_answer { - # - case $ANSWER in - y | Y | YES | yes | yEs | yeS | YEs | yES) - # If user answers "yes".do nothing. - ;; - *) - # If user answers anything but "yes", exit script - echo - echo $EXIT_LINE1 - echo $EXIT_LINE2 - echo - exit - ;; - esac - # - # Do a little variable clean-up - unset EXIT_LINE1 - unset EXIT_LINE2 - # + # + case $ANSWER in + y | Y | YES | yes | yEs | yeS | YEs | yES) + # If user answers "yes".do nothing. + ;; + *) + # If user answers anything but "yes", exit script + echo + echo $EXIT_LINE1 + echo $EXIT_LINE2 + echo + exit + ;; + esac + # + # Do a little variable clean-up + unset EXIT_LINE1 + unset EXIT_LINE2 + # } #End of process_answer function @@ -117,11 +117,11 @@ USER_ACCOUNT_RECORD=$(cat /etc/passwd | grep -w $USER_ACCOUNT) # if [ $? -eq 1 ] # If the account is not found, exit script then - echo - echo "Account, $USER_ACCOUNT, not found." - echo "Leaving the script..." - echo - exit + echo + echo "Account, $USER_ACCOUNT, not found." + echo "Leaving the script..." + echo + exit fi # echo @@ -153,56 +153,56 @@ echo ps -u $USER_ACCOUNT #List the processes running # case $? in - 1) # No processes running for this User Account - # - echo "There are no processes for this account currently running." - echo - ;; - 0) # Processes running for this User Account. - # Ask Script User if wants us to kill the processes. - # - unset ANSWER # I think this line is not needed - LINE1="Would you like me to kill the process(es)? [y/n]:" - get_answer - # - case $ANSWER in - y | Y | YES | yes | Yes | yEs | yeS | YEs | yES) # if user answer "yes", - #kill User Account processes - # - echo - # - # Clean-up temp file upon signals - # - trap "rm$USER_ACCOUNT_Running_Process.rpt" SIGTERM SIGINT SIGQUIT - # - # List user processes running - ps -u $USER_ACCOUNT > $USER_ACCOUNT_Running_Process.rpt - # - exec < $USER_ACCOUNT_Running_Process.rpt # Make report Std Input - # - read USER_PROCESS_REC # First record will be blank - read USER_PROCESS_REC - # - while [ $? -eq 0 ] - do - # obtain PID - USER_PID=$(echo $USER_PROCESS_REC | cut -d " " -f1) - kill -9 $USER_PID - echo "Killed process $USER_PID" - read USER_PROCESS_REC - done - # - echo - # - rm $USER_ACCOUNT_Running_Process.rpt # Remove temp report - ;; - *) # If user answers anything but "yes", do not kill. - echo - echo "Will not kill the process(es)." - echo - ;; - esac - ;; + 1) # No processes running for this User Account + # + echo "There are no processes for this account currently running." + echo + ;; + 0) # Processes running for this User Account. + # Ask Script User if wants us to kill the processes. + # + unset ANSWER # I think this line is not needed + LINE1="Would you like me to kill the process(es)? [y/n]:" + get_answer + # + case $ANSWER in + y | Y | YES | yes | Yes | yEs | yeS | YEs | yES) # if user answer "yes", + #kill User Account processes + # + echo + # + # Clean-up temp file upon signals + # + trap "rm$USER_ACCOUNT_Running_Process.rpt" SIGTERM SIGINT SIGQUIT + # + # List user processes running + ps -u $USER_ACCOUNT > $USER_ACCOUNT_Running_Process.rpt + # + exec < $USER_ACCOUNT_Running_Process.rpt # Make report Std Input + # + read USER_PROCESS_REC # First record will be blank + read USER_PROCESS_REC + # + while [ $? -eq 0 ] + do + # obtain PID + USER_PID=$(echo $USER_PROCESS_REC | cut -d " " -f1) + kill -9 $USER_PID + echo "Killed process $USER_PID" + read USER_PROCESS_REC + done + # + echo + # + rm $USER_ACCOUNT_Running_Process.rpt # Remove temp report + ;; + *) # If user answers anything but "yes", do not kill. + echo + echo "Will not kill the process(es)." + echo + ;; + esac + ;; esac ################################################################################### # diff --git a/codes/linux/tool/查看指定目录磁盘使用情况.sh b/codes/linux/tool/查看指定目录磁盘使用情况.sh index d3c46ea..64db731 100644 --- a/codes/linux/tool/查看指定目录磁盘使用情况.sh +++ b/codes/linux/tool/查看指定目录磁盘使用情况.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #DIRS="/var/log /home /opt" @@ -9,11 +9,11 @@ echo "Top Ten Disk Space Usage" echo "for ${DIRS} Directories" for DIR in ${DIRS} do - echo "" - echo "The ${DIR} Directory:" - du -S ${DIR} 2> /dev/null | - sort -rn | - sed '{11,$D; =}' | - sed 'N; s/\n/ /' | - gawk '{printf $1 ":" "\t" $2 "\t" $3 "\n"}' + echo "" + echo "The ${DIR} Directory:" + du -S ${DIR} 2> /dev/null | + sort -rn | + sed '{11,$D; =}' | + sed 'N; s/\n/ /' | + gawk '{printf $1 ":" "\t" $2 "\t" $3 "\n"}' done diff --git a/codes/shell/README.md b/codes/shell/README.md new file mode 100644 index 0000000..541bda1 --- /dev/null +++ b/codes/shell/README.md @@ -0,0 +1,8 @@ +# Shell 脚本大全 + +> **Shell 脚本大全** 精心收集、整理了 Linux 环境下的常见 Shell 脚本操作片段。 +> +> 当您面临以下问题时,**Shell 脚本大全** 也许可以给你一些借鉴: +> +> - 你想要执行某个操作,却不知 Shell 命令如何写 +> - 你想要快速掌握 Shell 基本用法 diff --git a/codes/shell/demos/README.md b/codes/shell/demos/README.md deleted file mode 100644 index 7f6702e..0000000 --- a/codes/shell/demos/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Shell 示例源码 - -> 本目录的代码是和 『[一篇文章让你彻底掌握 shell 语言](https://github.com/dunwu/linux-tutorial/blob/master/docs/linux/scripts/shell.md)』 相配套的示例代码。 diff --git a/codes/shell/demos/array-demo.sh b/codes/shell/demos/array-demo.sh deleted file mode 100644 index 5c412e2..0000000 --- a/codes/shell/demos/array-demo.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash - -# 创建数组 -nums=( [ 2 ] = 2 [ 0 ] = 0 [ 1 ] = 1 ) -colors=( red yellow "dark blue" ) - -# 访问数组的单个元素 -echo ${nums[1]} -# Output: 1 - -# 访问数组的所有元素 -echo ${colors[*]} -# Output: red yellow dark blue - -echo ${colors[@]} -# Output: red yellow dark blue - -printf "+ %s\n" ${colors[*]} -# Output: -# + red -# + yellow -# + dark -# + blue - -printf "+ %s\n" "${colors[*]}" -# Output: -# + red yellow dark blue - -printf "+ %s\n" "${colors[@]}" -# Output: -# + red -# + yellow -# + dark blue - -# 访问数组的部分元素 -echo ${nums[@]:0:2} -# Output: -# 0 1 - -# 访问数组长度 -echo ${#nums[*]} -# Output: -# 3 - -# 向数组中添加元素 -colors=( white "${colors[@]}" green black ) -echo ${colors[@]} -# Output: -# white red yellow dark blue green black - -# 从数组中删除元素 -unset nums[ 0 ] -echo ${nums[@]} -# Output: -# 1 2 diff --git a/codes/shell/demos/function/function-demo.sh b/codes/shell/demos/function/function-demo.sh deleted file mode 100644 index 4058469..0000000 --- a/codes/shell/demos/function/function-demo.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash - -calc() { - PS3="choose the oper: " - select oper in + - \* / # 生成操作符选择菜单 - do - echo -n "enter first num: " && read x # 读取输入参数 - echo -n "enter second num: " && read y # 读取输入参数 - exec - case ${oper} in - "+") - return $((${x} + ${y})) - ;; - "-") - return $((${x} - ${y})) - ;; - "*") - return $((${x} * ${y})) - ;; - "/") - return $((${x} / ${y})) - ;; - *) - echo "${oper} is not support!" - return 0 - ;; - esac - break - done -} - -calc -echo "the result is: $?" # $? 获取 calc 函数返回值 -# $ ./function-demo.sh -# 1) + -# 2) - -# 3) * -# 4) / -# choose the oper: 3 -# enter first num: 10 -# enter second num: 10 -# the result is: 100 diff --git a/codes/shell/demos/function/function-demo2.sh b/codes/shell/demos/function/function-demo2.sh deleted file mode 100644 index 9e5f40c..0000000 --- a/codes/shell/demos/function/function-demo2.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env bash - -x=0 -if [[ -n $1 ]]; then - echo "第一个参数为:$1" - x=$1 -else - echo "第一个参数为空" -fi - -y=0 -if [[ -n $2 ]]; then - echo "第二个参数为:$2" - y=$2 -else - echo "第二个参数为空" -fi - -paramsFunction() { - echo "函数第一个入参:$1" - echo "函数第二个入参:$2" -} - -paramsFunction ${x} ${y} diff --git a/codes/shell/demos/helloworld.sh b/codes/shell/demos/helloworld.sh deleted file mode 100644 index 9f3f770..0000000 --- a/codes/shell/demos/helloworld.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -echo "Hello, world!" diff --git a/codes/shell/demos/operator/operator-demo2.sh b/codes/shell/demos/operator/operator-demo2.sh deleted file mode 100644 index 166c539..0000000 --- a/codes/shell/demos/operator/operator-demo2.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash - -x=10 -if [[ -n $1 ]]; then - x=$1 -fi - -y=20 -if [[ -n $2 ]]; then - y=$2 -fi - -echo "x=${x}, y=${y}" - -if [[ ${x} -eq ${y} ]]; then - echo "${x} -eq ${y} : x 等于 y" -else - echo "${x} -eq ${y}: x 不等于 y" -fi - -if [[ ${x} -ne ${y} ]]; then - echo "${x} -ne ${y}: x 不等于 y" -else - echo "${x} -ne ${y}: x 等于 y" -fi - -if [[ ${x} -gt ${y} ]]; then - echo "${x} -gt ${y}: x 大于 y" -else - echo "${x} -gt ${y}: x 不大于 y" -fi - -if [[ ${x} -lt ${y} ]]; then - echo "${x} -lt ${y}: x 小于 y" -else - echo "${x} -lt ${y}: x 不小于 y" -fi - -if [[ ${x} -ge ${y} ]]; then - echo "${x} -ge ${y}: x 大于或等于 y" -else - echo "${x} -ge ${y}: x 小于 y" -fi - -if [[ ${x} -le ${y} ]]; then - echo "${x} -le ${y}: x 小于或等于 y" -else - echo "${x} -le ${y}: x 大于 y" -fi - -# Execute: ./operator-demo2.sh -# Output: -# x=10, y=20 -# 10 -eq 20: x 不等于 y -# 10 -ne 20: x 不等于 y -# 10 -gt 20: x 不大于 y -# 10 -lt 20: x 小于 y -# 10 -ge 20: x 小于 y -# 10 -le 20: x 小于或等于 y diff --git a/codes/shell/demos/operator/operator-demo3.sh b/codes/shell/demos/operator/operator-demo3.sh deleted file mode 100644 index e644253..0000000 --- a/codes/shell/demos/operator/operator-demo3.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bash - -x=10 -if [[ -n $1 ]]; then - x=$1 -fi - -y=20 -if [[ -n $2 ]]; then - y=$2 -fi - -echo "x=${x}, y=${y}" - -if [[ ${x} != ${y} ]]; then - echo "${x} != ${y} : x 不等于 y" -else - echo "${x} != ${y}: x 等于 y" -fi - -if [[ ${x} -lt 100 && ${y} -gt 15 ]]; then - echo "${x} 小于 100 且 ${y} 大于 15 : 返回 true" -else - echo "${x} 小于 100 且 ${y} 大于 15 : 返回 false" -fi - -if [[ ${x} -lt 100 || ${y} -gt 100 ]]; then - echo "${x} 小于 100 或 ${y} 大于 100 : 返回 true" -else - echo "${x} 小于 100 或 ${y} 大于 100 : 返回 false" -fi - -if [[ ${x} -lt 5 || ${y} -gt 100 ]]; then - echo "${x} 小于 5 或 ${y} 大于 100 : 返回 true" -else - echo "${x} 小于 5 或 ${y} 大于 100 : 返回 false" -fi - -# Execute: ./operator-demo3.sh -# Output: -# x=10, y=20 -# 10 != 20 : x 不等于 y -# 10 小于 100 且 20 大于 15 : 返回 true -# 10 小于 100 或 20 大于 100 : 返回 true -# 10 小于 5 或 20 大于 100 : 返回 false diff --git a/codes/shell/demos/operator/operator-demo6.sh b/codes/shell/demos/operator/operator-demo6.sh deleted file mode 100644 index b0a99b4..0000000 --- a/codes/shell/demos/operator/operator-demo6.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash - -file="/etc/hosts" - -if [[ -r ${file} ]]; then - echo "${file} 文件可读" -else - echo "${file} 文件不可读" -fi -if [[ -w ${file} ]]; then - echo "${file} 文件可写" -else - echo "${file} 文件不可写" -fi -if [[ -x ${file} ]]; then - echo "${file} 文件可执行" -else - echo "${file} 文件不可执行" -fi -if [[ -f ${file} ]]; then - echo "${file} 文件为普通文件" -else - echo "${file} 文件为特殊文件" -fi -if [[ -d ${file} ]]; then - echo "${file} 文件是个目录" -else - echo "${file} 文件不是个目录" -fi -if [[ -s ${file} ]]; then - echo "${file} 文件不为空" -else - echo "${file} 文件为空" -fi -if [[ -e ${file} ]]; then - echo "${file} 文件存在" -else - echo "${file} 文件不存在" -fi - -# Execute: ./operator-demo6.sh -# Output:(根据文件的实际情况,输出结果可能不同) -# /etc/hosts 文件可读 -# /etc/hosts 文件可写 -# /etc/hosts 文件不可执行 -# /etc/hosts 文件为普通文件 -# /etc/hosts 文件不是个目录 -# /etc/hosts 文件不为空 -# /etc/hosts 文件存在 diff --git a/codes/shell/demos/statement/break-demo.sh b/codes/shell/demos/statement/break-demo.sh deleted file mode 100644 index a00055b..0000000 --- a/codes/shell/demos/statement/break-demo.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -# 查找 10 以内第一个能整除 2 和 3 的正整数 -i=1 -while [[ ${i} -lt 10 ]]; do - if [[ $((i % 3)) -eq 0 ]] && [[ $((i % 2)) -eq 0 ]]; then - echo ${i} - break; - fi - i=`expr ${i} + 1` -done -# Output: 6 diff --git a/codes/shell/demos/statement/case-demo.sh b/codes/shell/demos/statement/case-demo.sh deleted file mode 100644 index 29f7067..0000000 --- a/codes/shell/demos/statement/case-demo.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash - -echo "input param: " $1 $2 $3 - -x=0 -if [[ -n $1 ]]; then - x=$1 -fi - -y=0 -if [[ -n $2 ]]; then - y=$2 -fi - -oper="" -if [[ -n $3 ]]; then - oper=$3 -fi - -exec -case ${oper} in - "+") - val=`expr ${x} + ${y}` - echo "${x} + ${y} = ${val}" - ;; - "-") - val=`expr ${x} - ${y}` - echo "${x} - ${y} = ${val}" - ;; - "*") - val=`expr ${x} \* ${y}` - echo "${x} * ${y} = ${val}" - ;; - "/") - val=`expr ${x} / ${y}` - echo "${x} / ${y} = ${val}" - ;; - *) - echo "Unknown oper!" - ;; -esac diff --git a/codes/shell/demos/statement/continue-demo.sh b/codes/shell/demos/statement/continue-demo.sh deleted file mode 100644 index ef8c221..0000000 --- a/codes/shell/demos/statement/continue-demo.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -# 打印10以内的奇数 -for (( i = 0; i < 10; i ++ )); do - if [[ $((i % 2)) -eq 0 ]]; then - continue; - fi - echo ${i} -done -# Output: -# 1 -# 3 -# 5 -# 7 -# 9 diff --git a/codes/shell/demos/statement/for-demo.sh b/codes/shell/demos/statement/for-demo.sh deleted file mode 100644 index 43c94a0..0000000 --- a/codes/shell/demos/statement/for-demo.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash - -################### for 语句 ################### -echo "print 0 to 9" -for (( j = 0; j < 10; j ++ )); do - echo ${j} -done -# Output: -# print 0 to 9 -# 0 -# 1 -# 2 -# 3 -# 4 -# 5 -# 6 -# 7 -# 8 -# 9 - -################### for in 语句 ################### -echo "print 1 to 5" -for i in {1..5}; do - echo ${i}; -done -# Output: -# print 1 to 5 -# 1 -# 2 -# 3 -# 4 -# 5 - -################### for in 语句遍历文件 ################### -DIR=/home/zp -for FILE in ${DIR}/*.sh; do - mv "$FILE" "${DIR}/scripts" -done -# 将 /home/zp 目录下所有 sh 文件拷贝到 /home/zp/scripts diff --git a/codes/shell/demos/statement/if-demo.sh b/codes/shell/demos/statement/if-demo.sh deleted file mode 100644 index 408e32a..0000000 --- a/codes/shell/demos/statement/if-demo.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash - -################### if 语句 ################### -# 写成一行 -if [[ 1 -eq 1 ]]; then - echo "1 -eq 1 result is: true"; -fi -# Output: 1 -eq 1 result is: true - -# 写成多行 -if [[ "abc" -eq "abc" ]] -then - echo ""abc" -eq "abc" result is: true" -fi -# Output: abc -eq abc result is: true - -################### if else 语句 ################### -if [[ 2 -ne 1 ]]; then - echo "true" -else - echo "false" -fi -# Output: true - -################### if elif else 语句 ################### -x=10 -y=20 -if [[ ${x} > ${y} ]]; then - echo "${x} > ${y}" -elif [[ ${x} < ${y} ]]; then - echo "${x} < ${y}" -else - echo "${x} = ${y}" -fi -# Output: 10 < 20 diff --git a/codes/shell/demos/statement/until-demo.sh b/codes/shell/demos/statement/until-demo.sh deleted file mode 100644 index 58a0fce..0000000 --- a/codes/shell/demos/statement/until-demo.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash - -x=0 -until [[ ${x} -ge 5 ]]; do - echo ${x} - x=`expr ${x} + 1` -done -# Output: -# 0 -# 1 -# 2 -# 3 -# 4 diff --git a/codes/shell/demos/statement/while-demo.sh b/codes/shell/demos/statement/while-demo.sh deleted file mode 100644 index 9492b0a..0000000 --- a/codes/shell/demos/statement/while-demo.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash - -### 0到9之间每个数的平方 -x=0 -### x小于10 -while [[ ${x} -lt 10 ]]; do - echo $((x * x)) - x=$((x + 1)) -done -# Output: -# 0 -# 1 -# 4 -# 9 -# 16 -# 25 -# 36 -# 49 -# 64 -# 81 diff --git a/codes/shell/demos/string-demo.sh b/codes/shell/demos/string-demo.sh deleted file mode 100644 index d3030fa..0000000 --- a/codes/shell/demos/string-demo.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash - -################### 单引号和双引号 ################### -################### 拼接字符串 ################### -# 使用单引号拼接 -name1='white' -str1='hello, '${name1}'' -str2='hello, ${name1}' -echo ${str1}_${str2} -# Output: -# hello, white_hello, ${name1} - -# 使用双引号拼接 -name2="black" -str3="hello, "${name2}"" -str4="hello, ${name2}" -echo ${str3}_${str4} -# Output: -# hello, black_hello, black - -################### 获取字符串长度 ################### -text="12345" -echo "${text} length is: ${#text}" -# Output: -# 12345 length is: 5 - -################### 获取字符串长度 ################### -text="12345" -echo ${text:2:2} -# Output: -# 34 - -################### 查找子字符串 ################### -text="hello" -echo `expr index "${text}" ll` -# Output: -# 3 - -################### 截取关键字左边内容 ################### -full_branch="feature/1.0.0" -branch=`echo ${full_branch#feature/}` -echo "branch is ${branch}" - -################### 截取关键字右边内容 ################### -full_version="0.0.1-SNAPSHOT" -version=`echo ${full_version%-SNAPSHOT}` -echo "version is ${version}" - -################### 判断字符串中是否包含子字符串 ################### -result=$(echo "${str}" | grep "feature/") -if [[ "$result" != "" ]]; then - echo "feature/ 是 ${str} 的子字符串" -else - echo "feature/ 不是 ${str} 的子字符串" -fi diff --git a/codes/shell/demos/variable-demo.sh b/codes/shell/demos/variable-demo.sh deleted file mode 100644 index db59ca7..0000000 --- a/codes/shell/demos/variable-demo.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash - -################### 声明变量 ################### -name="world" -echo "hello ${name}" -# Output: hello world - -################### 只读变量 ################### -rword="hello" -echo ${rword} -# Output: hello -readonly rword -# rword="bye" # 如果放开注释,执行时会报错 - -################### 删除变量 ################### -dword="hello" # 声明变量 -echo ${dword} # 输出变量值 -# Output: hello - -unset dword # 删除变量 -echo ${dword} -# Output: (空) diff --git a/codes/shell/示例脚本/mysql/SQL批处理执行脚本.sh b/codes/shell/mysql/SQL批处理执行脚本.sh similarity index 57% rename from codes/shell/示例脚本/mysql/SQL批处理执行脚本.sh rename to codes/shell/mysql/SQL批处理执行脚本.sh index 39d40f4..89c92fc 100644 --- a/codes/shell/示例脚本/mysql/SQL批处理执行脚本.sh +++ b/codes/shell/mysql/SQL批处理执行脚本.sh @@ -6,7 +6,7 @@ database='test' for f in `ls */*.sql` do - echo ${f}; - mysql -u${user} -p${password} -f ${database} -e "source $f"; + echo ${f}; + mysql -u${user} -p${password} -f ${database} -e "source $f"; done echo 'OK!' diff --git a/codes/shell/mysql/向数据库中插入数据.sh b/codes/shell/mysql/向数据库中插入数据.sh new file mode 100644 index 0000000..c57f31f --- /dev/null +++ b/codes/shell/mysql/向数据库中插入数据.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +# send data to the the table in the MYSQL database + +MYSQL=`which mysql` + +if [ $# -ne 2 ] +then + echo "Usage:mtest2 emplid lastname firstname salary" +else + #脚本变量一定要用双引号,字符串变量使用单引号 + statement=" insert into em_admin values(NULL, '$1', $2)" + $MYSQL emwjs -u test << EOF + $statement +EOF + if [ $? -eq 0 ] + then + echo Data successfully added + else + echo Problem adding data + fi +fi diff --git a/codes/shell/示例脚本/mysql/格式化输出数据.sh b/codes/shell/mysql/格式化输出数据.sh similarity index 90% rename from codes/shell/示例脚本/mysql/格式化输出数据.sh rename to codes/shell/mysql/格式化输出数据.sh index 93478f6..acf8969 100644 --- a/codes/shell/示例脚本/mysql/格式化输出数据.sh +++ b/codes/shell/mysql/格式化输出数据.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #redirecting SQL output to a variable @@ -6,7 +6,7 @@ MYSQL=`which mysql` dbs=`$MYSQL emwjs -u test -Bse 'show tables;'` for db in $dbs do - echo $db + echo $db done diff --git a/codes/shell/示例脚本/mysql/连接数据库并发送命令.sh b/codes/shell/mysql/连接数据库并发送命令.sh similarity index 90% rename from codes/shell/示例脚本/mysql/连接数据库并发送命令.sh rename to codes/shell/mysql/连接数据库并发送命令.sh index 70bccc6..6a022cb 100644 --- a/codes/shell/示例脚本/mysql/连接数据库并发送命令.sh +++ b/codes/shell/mysql/连接数据库并发送命令.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #连接数据库 mysql=`which mysql` diff --git a/codes/shell/demos/echo-demo.sh b/codes/shell/基本脚本/echo示例.sh similarity index 100% rename from codes/shell/demos/echo-demo.sh rename to codes/shell/基本脚本/echo示例.sh diff --git a/codes/shell/示例脚本/基本脚本/exit命令.sh b/codes/shell/基本脚本/exit命令.sh similarity index 88% rename from codes/shell/示例脚本/基本脚本/exit命令.sh rename to codes/shell/基本脚本/exit命令.sh index b40c9aa..a248af6 100644 --- a/codes/shell/示例脚本/基本脚本/exit命令.sh +++ b/codes/shell/基本脚本/exit命令.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #退出状态码,最大为255,超过则进行模运算 #testing the exit status diff --git a/codes/shell/demos/printf-demo.sh b/codes/shell/基本脚本/printf示例.sh similarity index 100% rename from codes/shell/demos/printf-demo.sh rename to codes/shell/基本脚本/printf示例.sh diff --git a/codes/shell/示例脚本/基本脚本/使用expr执行数学运算.sh b/codes/shell/基本脚本/使用expr执行数学运算.sh similarity index 84% rename from codes/shell/示例脚本/基本脚本/使用expr执行数学运算.sh rename to codes/shell/基本脚本/使用expr执行数学运算.sh index 8f8bf0a..7770a97 100644 --- a/codes/shell/示例脚本/基本脚本/使用expr执行数学运算.sh +++ b/codes/shell/基本脚本/使用expr执行数学运算.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #An example of using the expr command diff --git a/codes/shell/示例脚本/基本脚本/使用内联重定向计算表达式.sh b/codes/shell/基本脚本/使用内联重定向计算表达式.sh similarity index 89% rename from codes/shell/示例脚本/基本脚本/使用内联重定向计算表达式.sh rename to codes/shell/基本脚本/使用内联重定向计算表达式.sh index cec71c5..5ce4000 100644 --- a/codes/shell/示例脚本/基本脚本/使用内联重定向计算表达式.sh +++ b/codes/shell/基本脚本/使用内联重定向计算表达式.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash var1=10.45 var2=43.67 diff --git a/codes/shell/示例脚本/基本脚本/使用方括号执行数学运算.sh b/codes/shell/基本脚本/使用方括号执行数学运算.sh similarity index 82% rename from codes/shell/示例脚本/基本脚本/使用方括号执行数学运算.sh rename to codes/shell/基本脚本/使用方括号执行数学运算.sh index ffa0f4d..6c7870e 100644 --- a/codes/shell/示例脚本/基本脚本/使用方括号执行数学运算.sh +++ b/codes/shell/基本脚本/使用方括号执行数学运算.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash var1=10 var2=50 diff --git a/codes/shell/示例脚本/基本脚本/反引号的使用.sh b/codes/shell/基本脚本/反引号的使用.sh similarity index 87% rename from codes/shell/示例脚本/基本脚本/反引号的使用.sh rename to codes/shell/基本脚本/反引号的使用.sh index ba50293..8fde29c 100644 --- a/codes/shell/示例脚本/基本脚本/反引号的使用.sh +++ b/codes/shell/基本脚本/反引号的使用.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #using the backtick character 会把反引号里面当作一条命令来执行 diff --git a/codes/shell/示例脚本/基本脚本/变量使用示例.sh b/codes/shell/基本脚本/变量使用示例.sh similarity index 100% rename from codes/shell/示例脚本/基本脚本/变量使用示例.sh rename to codes/shell/基本脚本/变量使用示例.sh diff --git a/codes/shell/示例脚本/基本脚本/在脚本中使用bc.sh b/codes/shell/基本脚本/在脚本中使用bc.sh similarity index 82% rename from codes/shell/示例脚本/基本脚本/在脚本中使用bc.sh rename to codes/shell/基本脚本/在脚本中使用bc.sh index c327846..b868434 100644 --- a/codes/shell/示例脚本/基本脚本/在脚本中使用bc.sh +++ b/codes/shell/基本脚本/在脚本中使用bc.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash var1=100 var2=45 diff --git a/codes/shell/示例脚本/基本脚本/字符串使用示例.sh b/codes/shell/基本脚本/字符串使用示例.sh similarity index 100% rename from codes/shell/示例脚本/基本脚本/字符串使用示例.sh rename to codes/shell/基本脚本/字符串使用示例.sh diff --git a/codes/shell/示例脚本/基本脚本/数组使用示例.sh b/codes/shell/基本脚本/数组使用示例.sh similarity index 100% rename from codes/shell/示例脚本/基本脚本/数组使用示例.sh rename to codes/shell/基本脚本/数组使用示例.sh diff --git a/codes/shell/示例脚本/基本脚本/显示时间和登录者.sh b/codes/shell/基本脚本/显示时间和登录者.sh similarity index 90% rename from codes/shell/示例脚本/基本脚本/显示时间和登录者.sh rename to codes/shell/基本脚本/显示时间和登录者.sh index 4ac3b2f..d53162b 100644 --- a/codes/shell/示例脚本/基本脚本/显示时间和登录者.sh +++ b/codes/shell/基本脚本/显示时间和登录者.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #This script displays the date and who's logged on diff --git a/codes/shell/示例脚本/基本脚本/显示系统变量和转义字符.sh b/codes/shell/基本脚本/显示系统变量和转义字符.sh similarity index 89% rename from codes/shell/示例脚本/基本脚本/显示系统变量和转义字符.sh rename to codes/shell/基本脚本/显示系统变量和转义字符.sh index 1c9b812..03b4eb7 100644 --- a/codes/shell/示例脚本/基本脚本/显示系统变量和转义字符.sh +++ b/codes/shell/基本脚本/显示系统变量和转义字符.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #display user information from system diff --git a/codes/shell/demos/comment-demo.sh b/codes/shell/基本脚本/注释示例.sh similarity index 100% rename from codes/shell/demos/comment-demo.sh rename to codes/shell/基本脚本/注释示例.sh diff --git a/codes/shell/示例脚本/基本脚本/通过反引号获得当前日期并生成唯一文件名.sh b/codes/shell/基本脚本/通过反引号获得当前日期并生成唯一文件名.sh similarity index 83% rename from codes/shell/示例脚本/基本脚本/通过反引号获得当前日期并生成唯一文件名.sh rename to codes/shell/基本脚本/通过反引号获得当前日期并生成唯一文件名.sh index bc6d691..088afd5 100644 --- a/codes/shell/示例脚本/基本脚本/通过反引号获得当前日期并生成唯一文件名.sh +++ b/codes/shell/基本脚本/通过反引号获得当前日期并生成唯一文件名.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #copy the /usr/bin directory listing to a log file diff --git a/codes/shell/示例脚本/控制/定时执行脚本.sh b/codes/shell/控制/定时执行脚本.sh similarity index 68% rename from codes/shell/示例脚本/控制/定时执行脚本.sh rename to codes/shell/控制/定时执行脚本.sh index 44a4049..e070c0d 100644 --- a/codes/shell/示例脚本/控制/定时执行脚本.sh +++ b/codes/shell/控制/定时执行脚本.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing the at command diff --git a/codes/shell/示例脚本/控制/捕捉信号.sh b/codes/shell/控制/捕捉信号.sh similarity index 67% rename from codes/shell/示例脚本/控制/捕捉信号.sh rename to codes/shell/控制/捕捉信号.sh index 61d5d47..91dfad3 100644 --- a/codes/shell/示例脚本/控制/捕捉信号.sh +++ b/codes/shell/控制/捕捉信号.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing signal trapping @@ -10,7 +10,7 @@ count=1 while [ $count -le 10 ] do - echo "Loop #$count" - sleep 5 - count=$[ $count + 1 ] + echo "Loop #$count" + sleep 5 + count=$[ $count + 1 ] done diff --git a/codes/shell/示例脚本/控制/捕捉脚本的退出.sh b/codes/shell/控制/捕捉脚本的退出.sh similarity index 55% rename from codes/shell/示例脚本/控制/捕捉脚本的退出.sh rename to codes/shell/控制/捕捉脚本的退出.sh index fdccacf..70abca9 100644 --- a/codes/shell/示例脚本/控制/捕捉脚本的退出.sh +++ b/codes/shell/控制/捕捉脚本的退出.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # trapping the script exit @@ -7,7 +7,7 @@ trap "echobyebye" EXIT count=1 while [ $count -le 5 ] do - echo "Loop #$count" - sleep 3 - count=$[ $count + 1 ] + echo "Loop #$count" + sleep 3 + count=$[ $count + 1 ] done diff --git a/codes/shell/示例脚本/控制/移除捕捉.sh b/codes/shell/控制/移除捕捉.sh similarity index 66% rename from codes/shell/示例脚本/控制/移除捕捉.sh rename to codes/shell/控制/移除捕捉.sh index 60a5e7e..306abdc 100644 --- a/codes/shell/示例脚本/控制/移除捕捉.sh +++ b/codes/shell/控制/移除捕捉.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # removeing a set trap @@ -7,9 +7,9 @@ trap "echobyebye" EXIT count=1 while [ $count -le 5 ] do - echo "Loop #$count" - sleep 3 - count=$[ $count + 1 ] + echo "Loop #$count" + sleep 3 + count=$[ $count + 1 ] done #移除捕捉 trap - EXIT diff --git a/codes/shell/示例脚本/操作符/比较符使用示例.sh b/codes/shell/操作符/关系运算符.sh similarity index 50% rename from codes/shell/示例脚本/操作符/比较符使用示例.sh rename to codes/shell/操作符/关系运算符.sh index 166c539..c3af9f4 100644 --- a/codes/shell/示例脚本/操作符/比较符使用示例.sh +++ b/codes/shell/操作符/关系运算符.sh @@ -2,53 +2,52 @@ x=10 if [[ -n $1 ]]; then - x=$1 + x=$1 fi y=20 if [[ -n $2 ]]; then - y=$2 + y=$2 fi echo "x=${x}, y=${y}" if [[ ${x} -eq ${y} ]]; then - echo "${x} -eq ${y} : x 等于 y" + echo "${x} -eq ${y} : x 等于 y" else - echo "${x} -eq ${y}: x 不等于 y" + echo "${x} -eq ${y}: x 不等于 y" fi if [[ ${x} -ne ${y} ]]; then - echo "${x} -ne ${y}: x 不等于 y" + echo "${x} -ne ${y}: x 不等于 y" else - echo "${x} -ne ${y}: x 等于 y" + echo "${x} -ne ${y}: x 等于 y" fi if [[ ${x} -gt ${y} ]]; then - echo "${x} -gt ${y}: x 大于 y" + echo "${x} -gt ${y}: x 大于 y" else - echo "${x} -gt ${y}: x 不大于 y" + echo "${x} -gt ${y}: x 不大于 y" fi if [[ ${x} -lt ${y} ]]; then - echo "${x} -lt ${y}: x 小于 y" + echo "${x} -lt ${y}: x 小于 y" else - echo "${x} -lt ${y}: x 不小于 y" + echo "${x} -lt ${y}: x 不小于 y" fi if [[ ${x} -ge ${y} ]]; then - echo "${x} -ge ${y}: x 大于或等于 y" + echo "${x} -ge ${y}: x 大于或等于 y" else - echo "${x} -ge ${y}: x 小于 y" + echo "${x} -ge ${y}: x 小于 y" fi if [[ ${x} -le ${y} ]]; then - echo "${x} -le ${y}: x 小于或等于 y" + echo "${x} -le ${y}: x 小于或等于 y" else - echo "${x} -le ${y}: x 大于 y" + echo "${x} -le ${y}: x 大于 y" fi -# Execute: ./operator-demo2.sh # Output: # x=10, y=20 # 10 -eq 20: x 不等于 y diff --git a/codes/shell/demos/operator/operator-demo5.sh b/codes/shell/操作符/字符串运算符.sh similarity index 50% rename from codes/shell/demos/operator/operator-demo5.sh rename to codes/shell/操作符/字符串运算符.sh index 0182f1d..3a3c647 100644 --- a/codes/shell/demos/operator/operator-demo5.sh +++ b/codes/shell/操作符/字符串运算符.sh @@ -1,48 +1,48 @@ + #!/usr/bin/env bash x="abc" if [[ -n $1 ]]; then - x=$1 + x=$1 fi y="xyz" if [[ -n $2 ]]; then - y=$2 + y=$2 fi echo "x=${x}, y=${y}" if [[ ${x} = ${y} ]]; then - echo "${x} = ${y} : x 等于 y" + echo "${x} = ${y} : x 等于 y" else - echo "${x} = ${y}: x 不等于 y" + echo "${x} = ${y}: x 不等于 y" fi if [[ ${x} != ${y} ]]; then - echo "${x} != ${y} : x 不等于 y" + echo "${x} != ${y} : x 不等于 y" else - echo "${x} != ${y}: x 等于 y" + echo "${x} != ${y}: x 等于 y" fi if [[ -z ${x} ]]; then - echo "-z ${x} : 字符串长度为 0" + echo "-z ${x} : 字符串长度为 0" else - echo "-z ${x} : 字符串长度不为 0" + echo "-z ${x} : 字符串长度不为 0" fi if [[ -n "${x}" ]]; then - echo "-n ${x} : 字符串长度不为 0" + echo "-n ${x} : 字符串长度不为 0" else - echo "-n ${x} : 字符串长度为 0" + echo "-n ${x} : 字符串长度为 0" fi if [[ ${x} ]]; then - echo "${x} : 字符串不为空" + echo "${x} : 字符串不为空" else - echo "${x} : 字符串为空" + echo "${x} : 字符串为空" fi -# Execute: ./operator-demo5.sh # Output: # x=abc, y=xyz # abc = xyz: x 不等于 y diff --git a/codes/shell/示例脚本/操作符/比较符使用示例2.sh b/codes/shell/操作符/布尔运算符.sh similarity index 50% rename from codes/shell/示例脚本/操作符/比较符使用示例2.sh rename to codes/shell/操作符/布尔运算符.sh index e644253..abd0f72 100644 --- a/codes/shell/示例脚本/操作符/比较符使用示例2.sh +++ b/codes/shell/操作符/布尔运算符.sh @@ -2,41 +2,40 @@ x=10 if [[ -n $1 ]]; then - x=$1 + x=$1 fi y=20 if [[ -n $2 ]]; then - y=$2 + y=$2 fi echo "x=${x}, y=${y}" if [[ ${x} != ${y} ]]; then - echo "${x} != ${y} : x 不等于 y" + echo "${x} != ${y} : x 不等于 y" else - echo "${x} != ${y}: x 等于 y" + echo "${x} != ${y}: x 等于 y" fi if [[ ${x} -lt 100 && ${y} -gt 15 ]]; then - echo "${x} 小于 100 且 ${y} 大于 15 : 返回 true" + echo "${x} 小于 100 且 ${y} 大于 15 : 返回 true" else - echo "${x} 小于 100 且 ${y} 大于 15 : 返回 false" + echo "${x} 小于 100 且 ${y} 大于 15 : 返回 false" fi if [[ ${x} -lt 100 || ${y} -gt 100 ]]; then - echo "${x} 小于 100 或 ${y} 大于 100 : 返回 true" + echo "${x} 小于 100 或 ${y} 大于 100 : 返回 true" else - echo "${x} 小于 100 或 ${y} 大于 100 : 返回 false" + echo "${x} 小于 100 或 ${y} 大于 100 : 返回 false" fi if [[ ${x} -lt 5 || ${y} -gt 100 ]]; then - echo "${x} 小于 5 或 ${y} 大于 100 : 返回 true" + echo "${x} 小于 5 或 ${y} 大于 100 : 返回 true" else - echo "${x} 小于 5 或 ${y} 大于 100 : 返回 false" + echo "${x} 小于 5 或 ${y} 大于 100 : 返回 false" fi -# Execute: ./operator-demo3.sh # Output: # x=10, y=20 # 10 != 20 : x 不等于 y diff --git a/codes/shell/示例脚本/操作符/文件目录判断使用示例.sh b/codes/shell/操作符/文件测试运算符.sh similarity index 51% rename from codes/shell/示例脚本/操作符/文件目录判断使用示例.sh rename to codes/shell/操作符/文件测试运算符.sh index b0a99b4..b57d151 100644 --- a/codes/shell/示例脚本/操作符/文件目录判断使用示例.sh +++ b/codes/shell/操作符/文件测试运算符.sh @@ -3,42 +3,41 @@ file="/etc/hosts" if [[ -r ${file} ]]; then - echo "${file} 文件可读" + echo "${file} 文件可读" else - echo "${file} 文件不可读" + echo "${file} 文件不可读" fi if [[ -w ${file} ]]; then - echo "${file} 文件可写" + echo "${file} 文件可写" else - echo "${file} 文件不可写" + echo "${file} 文件不可写" fi if [[ -x ${file} ]]; then - echo "${file} 文件可执行" + echo "${file} 文件可执行" else - echo "${file} 文件不可执行" + echo "${file} 文件不可执行" fi if [[ -f ${file} ]]; then - echo "${file} 文件为普通文件" + echo "${file} 文件为普通文件" else - echo "${file} 文件为特殊文件" + echo "${file} 文件为特殊文件" fi if [[ -d ${file} ]]; then - echo "${file} 文件是个目录" + echo "${file} 文件是个目录" else - echo "${file} 文件不是个目录" + echo "${file} 文件不是个目录" fi if [[ -s ${file} ]]; then - echo "${file} 文件不为空" + echo "${file} 文件不为空" else - echo "${file} 文件为空" + echo "${file} 文件为空" fi if [[ -e ${file} ]]; then - echo "${file} 文件存在" + echo "${file} 文件存在" else - echo "${file} 文件不存在" + echo "${file} 文件不存在" fi -# Execute: ./operator-demo6.sh # Output:(根据文件的实际情况,输出结果可能不同) # /etc/hosts 文件可读 # /etc/hosts 文件可写 diff --git a/codes/shell/demos/operator/operator-demo.sh b/codes/shell/操作符/算术运算符.sh similarity index 83% rename from codes/shell/demos/operator/operator-demo.sh rename to codes/shell/操作符/算术运算符.sh index 8e62f92..270f89f 100644 --- a/codes/shell/demos/operator/operator-demo.sh +++ b/codes/shell/操作符/算术运算符.sh @@ -2,12 +2,12 @@ x=10 if [[ -n $1 ]]; then - x=$1 + x=$1 fi y=20 if [[ -n $2 ]]; then - y=$2 + y=$2 fi echo "x=${x}, y=${y}" @@ -28,13 +28,13 @@ val=`expr ${y} % ${x}` echo "${y} % ${x} = $val" if [[ ${x} == ${y} ]]; then - echo "${x} = ${y}" + echo "${x} = ${y}" fi if [[ ${x} != ${y} ]]; then - echo "${x} != ${y}" + echo "${x} != ${y}" fi -# Execute: ./operator-demo.sh +# Execute: ./算术运算符.sh # Output: # x=10, y=20 # 10 + 20 = 30 @@ -44,7 +44,7 @@ fi # 20 % 10 = 0 # 10 != 20 -# Execute: ./operator-demo.sh 10 30 +# Execute: ./算术运算符.sh 10 30 # Output: # x=10, y=30 # 10 + 30 = 40 diff --git a/codes/shell/demos/operator/operator-demo4.sh b/codes/shell/操作符/逻辑运算符.sh similarity index 54% rename from codes/shell/demos/operator/operator-demo4.sh rename to codes/shell/操作符/逻辑运算符.sh index e0ac1c4..c622313 100644 --- a/codes/shell/demos/operator/operator-demo4.sh +++ b/codes/shell/操作符/逻辑运算符.sh @@ -2,31 +2,30 @@ x=10 if [[ -n $1 ]]; then - x=$1 + x=$1 fi y=20 if [[ -n $2 ]]; then - y=$2 + y=$2 fi echo "x=${x}, y=${y}" if [[ ${x} -lt 100 && ${y} -gt 100 ]] then - echo "${x} -lt 100 && ${y} -gt 100 返回 true" + echo "${x} -lt 100 && ${y} -gt 100 返回 true" else - echo "${x} -lt 100 && ${y} -gt 100 返回 false" + echo "${x} -lt 100 && ${y} -gt 100 返回 false" fi if [[ ${x} -lt 100 || ${y} -gt 100 ]] then - echo "${x} -lt 100 || ${y} -gt 100 返回 true" + echo "${x} -lt 100 || ${y} -gt 100 返回 true" else - echo "${x} -lt 100 || ${y} -gt 100 返回 false" + echo "${x} -lt 100 || ${y} -gt 100 返回 false" fi -# Execute: ./operator-demo4.sh # Output: # x=10, y=20 # 10 -lt 100 && 20 -gt 100 返回 false diff --git a/codes/shell/示例脚本/查找替换文本/gawk/gawk.sh b/codes/shell/查找替换文本/gawk/gawk.sh similarity index 85% rename from codes/shell/示例脚本/查找替换文本/gawk/gawk.sh rename to codes/shell/查找替换文本/gawk/gawk.sh index a6d98fc..6baee2e 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/gawk.sh +++ b/codes/shell/查找替换文本/gawk/gawk.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash BEGIN { print "The latest list of users and shells" @@ -8,7 +8,7 @@ FS=":" } { - print $1 " " $7 + print $1 " " $7 } END { diff --git a/codes/shell/示例脚本/查找替换文本/gawk/gawk函数库 b/codes/shell/查找替换文本/gawk/gawk函数库 similarity index 55% rename from codes/shell/示例脚本/查找替换文本/gawk/gawk函数库 rename to codes/shell/查找替换文本/gawk/gawk函数库 index c6673c1..99bc48d 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/gawk函数库 +++ b/codes/shell/查找替换文本/gawk/gawk函数库 @@ -5,8 +5,8 @@ function myprint() printf "%-16s - %s", $1, $4 } -function myrand(limit) +function myrand ( limit ) { - return int(limit * rand()) +return int ( limit * rand ( ) ) } diff --git a/codes/shell/查找替换文本/gawk/gawk脚本 b/codes/shell/查找替换文本/gawk/gawk脚本 new file mode 100644 index 0000000..1028bcd --- /dev/null +++ b/codes/shell/查找替换文本/gawk/gawk脚本 @@ -0,0 +1,8 @@ +#!/bin/bash + +BEGIN{ FS="\n"; +RS=""} +{ +myprint() + +} diff --git a/codes/shell/示例脚本/查找替换文本/gawk/script b/codes/shell/查找替换文本/gawk/script similarity index 100% rename from codes/shell/示例脚本/查找替换文本/gawk/script rename to codes/shell/查找替换文本/gawk/script diff --git a/codes/shell/示例脚本/查找替换文本/gawk/test b/codes/shell/查找替换文本/gawk/test similarity index 100% rename from codes/shell/示例脚本/查找替换文本/gawk/test rename to codes/shell/查找替换文本/gawk/test diff --git a/codes/shell/示例脚本/查找替换文本/gawk/使用变量.sh b/codes/shell/查找替换文本/gawk/使用变量.sh similarity index 97% rename from codes/shell/示例脚本/查找替换文本/gawk/使用变量.sh rename to codes/shell/查找替换文本/gawk/使用变量.sh index 817bd65..51f2651 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/使用变量.sh +++ b/codes/shell/查找替换文本/gawk/使用变量.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #使用内建变量 diff --git a/codes/shell/示例脚本/查找替换文本/gawk/使用模式,结构化命令.sh b/codes/shell/查找替换文本/gawk/使用模式,结构化命令.sh similarity index 95% rename from codes/shell/示例脚本/查找替换文本/gawk/使用模式,结构化命令.sh rename to codes/shell/查找替换文本/gawk/使用模式,结构化命令.sh index db7b78c..6e61f42 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/使用模式,结构化命令.sh +++ b/codes/shell/查找替换文本/gawk/使用模式,结构化命令.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #正则表达式 diff --git a/codes/shell/示例脚本/查找替换文本/gawk/自定义函数.sh b/codes/shell/查找替换文本/gawk/自定义函数.sh similarity index 86% rename from codes/shell/示例脚本/查找替换文本/gawk/自定义函数.sh rename to codes/shell/查找替换文本/gawk/自定义函数.sh index 81e13af..a026581 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/自定义函数.sh +++ b/codes/shell/查找替换文本/gawk/自定义函数.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #gawk 自定义函数 diff --git a/codes/shell/示例脚本/查找替换文本/gawk/调用函数库和脚本.sh b/codes/shell/查找替换文本/gawk/调用函数库和脚本.sh similarity index 78% rename from codes/shell/示例脚本/查找替换文本/gawk/调用函数库和脚本.sh rename to codes/shell/查找替换文本/gawk/调用函数库和脚本.sh index 0ffaa67..fc871ed 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/调用函数库和脚本.sh +++ b/codes/shell/查找替换文本/gawk/调用函数库和脚本.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #使用函数库和gawk脚本 diff --git a/codes/shell/示例脚本/查找替换文本/gawk/输出.sh b/codes/shell/查找替换文本/gawk/输出.sh similarity index 97% rename from codes/shell/示例脚本/查找替换文本/gawk/输出.sh rename to codes/shell/查找替换文本/gawk/输出.sh index cd60948..a26f5c7 100644 --- a/codes/shell/示例脚本/查找替换文本/gawk/输出.sh +++ b/codes/shell/查找替换文本/gawk/输出.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #print用于产生简单输出 #多个表达式的字符串值之间用输出字段分隔符分开 @@ -62,5 +62,5 @@ END{ for(c in pop) printf("%15-s%6d\n", c, pop[c]) | "sort -nk 2"; close("sort - #在同一个程序中,如果你写了一个文件,而待会儿想要读取它,那么就需要调用close。 #某一时刻,同时处于打开状态的文件或管道数量最大值由实现定义。 -close ( " sort -nk 2 " ) +close ( " sort -nk 2 " ) diff --git a/codes/shell/查找替换文本/regex/目录文件计数.sh b/codes/shell/查找替换文本/regex/目录文件计数.sh new file mode 100644 index 0000000..af04836 --- /dev/null +++ b/codes/shell/查找替换文本/regex/目录文件计数.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +# count number of files in your PATH + +mypath=`echo $PATH | sed 's/:/ /g'` +count=0 +for directory in $mypath +do + check=`ls $directory` + echo $check + for item in $check + do + count=$[ $count + 1 ] + done + echo "$directory - $count" + count=0 +done + diff --git a/codes/shell/示例脚本/查找替换文本/regex/邮件验证.sh b/codes/shell/查找替换文本/regex/邮件验证.sh similarity index 84% rename from codes/shell/示例脚本/查找替换文本/regex/邮件验证.sh rename to codes/shell/查找替换文本/regex/邮件验证.sh index 1857ac8..e5e28ab 100644 --- a/codes/shell/示例脚本/查找替换文本/regex/邮件验证.sh +++ b/codes/shell/查找替换文本/regex/邮件验证.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #验证邮件 diff --git a/codes/shell/示例脚本/查找替换文本/sed/sed文件操作.sh b/codes/shell/查找替换文本/sed/sed文件操作.sh similarity index 93% rename from codes/shell/示例脚本/查找替换文本/sed/sed文件操作.sh rename to codes/shell/查找替换文本/sed/sed文件操作.sh index 046001e..9185c9e 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/sed文件操作.sh +++ b/codes/shell/查找替换文本/sed/sed文件操作.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #向文件写入 sed '1,2w test1' test1 diff --git a/codes/shell/示例脚本/查找替换文本/sed/sed编辑器基础.sh b/codes/shell/查找替换文本/sed/sed编辑器基础.sh similarity index 99% rename from codes/shell/示例脚本/查找替换文本/sed/sed编辑器基础.sh rename to codes/shell/查找替换文本/sed/sed编辑器基础.sh index f6ce62d..06e9c46 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/sed编辑器基础.sh +++ b/codes/shell/查找替换文本/sed/sed编辑器基础.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #sed编辑器基础 diff --git a/codes/shell/示例脚本/查找替换文本/sed/test b/codes/shell/查找替换文本/sed/test similarity index 100% rename from codes/shell/示例脚本/查找替换文本/sed/test rename to codes/shell/查找替换文本/sed/test diff --git a/codes/shell/示例脚本/查找替换文本/sed/保持空间.sh b/codes/shell/查找替换文本/sed/保持空间.sh similarity index 92% rename from codes/shell/示例脚本/查找替换文本/sed/保持空间.sh rename to codes/shell/查找替换文本/sed/保持空间.sh index 3c75f7d..0772420 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/保持空间.sh +++ b/codes/shell/查找替换文本/sed/保持空间.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #h将模式空间保存到保持空间 #H将模式空间附加到保持空间 diff --git a/codes/shell/示例脚本/查找替换文本/sed/删除指定的空白行和删除html标签.sh b/codes/shell/查找替换文本/sed/删除指定的空白行和删除html标签.sh similarity index 93% rename from codes/shell/示例脚本/查找替换文本/sed/删除指定的空白行和删除html标签.sh rename to codes/shell/查找替换文本/sed/删除指定的空白行和删除html标签.sh index 2dcdd57..d37ebaa 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/删除指定的空白行和删除html标签.sh +++ b/codes/shell/查找替换文本/sed/删除指定的空白行和删除html标签.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #多个空格只保留一个 #sed '/./,/^$/!d' test diff --git a/codes/shell/示例脚本/查找替换文本/sed/在脚本中使用sed.sh b/codes/shell/查找替换文本/sed/在脚本中使用sed.sh similarity index 80% rename from codes/shell/示例脚本/查找替换文本/sed/在脚本中使用sed.sh rename to codes/shell/查找替换文本/sed/在脚本中使用sed.sh index 75142e4..5a1a5fa 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/在脚本中使用sed.sh +++ b/codes/shell/查找替换文本/sed/在脚本中使用sed.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # shell wrapper for sed editor script to reverse lines diff --git a/codes/shell/示例脚本/查找替换文本/sed/排除命令.sh b/codes/shell/查找替换文本/sed/排除命令.sh similarity index 100% rename from codes/shell/示例脚本/查找替换文本/sed/排除命令.sh rename to codes/shell/查找替换文本/sed/排除命令.sh diff --git a/codes/shell/示例脚本/查找替换文本/sed/模式替代.sh b/codes/shell/查找替换文本/sed/模式替代.sh similarity index 95% rename from codes/shell/示例脚本/查找替换文本/sed/模式替代.sh rename to codes/shell/查找替换文本/sed/模式替代.sh index 8682f6e..70585d1 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/模式替代.sh +++ b/codes/shell/查找替换文本/sed/模式替代.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #and符号,代表替换命令中的匹配模式,不管预定义模式是什么文本,都可以用and符号替换,and符号会提取匹配替换命令中指定替换模式中的所有字符串 echo "The cat sleeps in his hat" | sed 's/.at/"&"/g' diff --git a/codes/shell/示例脚本/查找替换文本/sed/测试.sh b/codes/shell/查找替换文本/sed/测试.sh similarity index 91% rename from codes/shell/示例脚本/查找替换文本/sed/测试.sh rename to codes/shell/查找替换文本/sed/测试.sh index 65ef706..88befd7 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/测试.sh +++ b/codes/shell/查找替换文本/sed/测试.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #测试,如果测试成功,如果没有标签,sed会跳转到结尾,如果有标签,就跳转到标签,如果测试失败,则不会跳转 sed -n '{s/first/matched/; t; s/This is the/No match on/}' test diff --git a/codes/shell/示例脚本/查找替换文本/sed/给文件中的行编号.sh b/codes/shell/查找替换文本/sed/给文件中的行编号.sh similarity index 62% rename from codes/shell/示例脚本/查找替换文本/sed/给文件中的行编号.sh rename to codes/shell/查找替换文本/sed/给文件中的行编号.sh index 07bd0e6..9ed6f14 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/给文件中的行编号.sh +++ b/codes/shell/查找替换文本/sed/给文件中的行编号.sh @@ -1,3 +1,3 @@ -#!/bin/bash +#!/usr/bin/env bash sed '=' test | sed 'N; s/\n/ /' diff --git a/codes/shell/示例脚本/查找替换文本/sed/跳转.sh b/codes/shell/查找替换文本/sed/跳转.sh similarity index 92% rename from codes/shell/示例脚本/查找替换文本/sed/跳转.sh rename to codes/shell/查找替换文本/sed/跳转.sh index 69eff6b..a352ad5 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/跳转.sh +++ b/codes/shell/查找替换文本/sed/跳转.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #跳转到指定脚本 sed '{/first/b jump1; s/This is the/No jump on/; :jump1; s/This is the/Jump here on/}' test diff --git a/codes/shell/示例脚本/查找替换文本/sed/输出末尾指定行数的数据.sh b/codes/shell/查找替换文本/sed/输出末尾指定行数的数据.sh similarity index 78% rename from codes/shell/示例脚本/查找替换文本/sed/输出末尾指定行数的数据.sh rename to codes/shell/查找替换文本/sed/输出末尾指定行数的数据.sh index 7e4efc9..8bddf0e 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/输出末尾指定行数的数据.sh +++ b/codes/shell/查找替换文本/sed/输出末尾指定行数的数据.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #输出末尾10行数据 diff --git a/codes/shell/示例脚本/查找替换文本/sed/重定向sed输出.sh b/codes/shell/查找替换文本/sed/重定向sed输出.sh similarity index 73% rename from codes/shell/示例脚本/查找替换文本/sed/重定向sed输出.sh rename to codes/shell/查找替换文本/sed/重定向sed输出.sh index 715a75b..674afaa 100644 --- a/codes/shell/示例脚本/查找替换文本/sed/重定向sed输出.sh +++ b/codes/shell/查找替换文本/sed/重定向sed输出.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # add commas to numbers in factorial answer @@ -8,8 +8,8 @@ number=$1 while [ $counter -le $number ] do - factorial=$[ $factorial * $counter ] - counter=$[ $counter + 1 ] + factorial=$[ $factorial * $counter ] + counter=$[ $counter + 1 ] done result=`echo $factorial | sed '{ diff --git a/codes/shell/示例脚本/README.md b/codes/shell/示例脚本/README.md deleted file mode 100644 index 8838660..0000000 --- a/codes/shell/示例脚本/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Shell 脚本实战 - -> 本目录的代码是本人在学习、开发中收集、总结的一些面向实战的 Shell 脚本代码。 diff --git a/codes/shell/示例脚本/mysql/向数据库中插入数据.sh b/codes/shell/示例脚本/mysql/向数据库中插入数据.sh deleted file mode 100644 index 73c73d1..0000000 --- a/codes/shell/示例脚本/mysql/向数据库中插入数据.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -# send data to the the table in the MYSQL database - -MYSQL=`which mysql` - -if [ $# -ne 2 ] -then - echo "Usage:mtest2 emplid lastname firstname salary" -else - #脚本变量一定要用双引号,字符串变量使用单引号 - statement=" insert into em_admin values(NULL, '$1', $2)" - $MYSQL emwjs -u test << EOF - $statement -EOF - if [ $? -eq 0 ] - then - echo Data successfully added - else - echo Problem adding data - fi -fi diff --git a/codes/shell/示例脚本/操作符/字符串比较判断示例.sh b/codes/shell/示例脚本/操作符/字符串比较判断示例.sh deleted file mode 100644 index 0182f1d..0000000 --- a/codes/shell/示例脚本/操作符/字符串比较判断示例.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env bash - -x="abc" -if [[ -n $1 ]]; then - x=$1 -fi - -y="xyz" -if [[ -n $2 ]]; then - y=$2 -fi - -echo "x=${x}, y=${y}" - -if [[ ${x} = ${y} ]]; then - echo "${x} = ${y} : x 等于 y" -else - echo "${x} = ${y}: x 不等于 y" -fi - -if [[ ${x} != ${y} ]]; then - echo "${x} != ${y} : x 不等于 y" -else - echo "${x} != ${y}: x 等于 y" -fi - -if [[ -z ${x} ]]; then - echo "-z ${x} : 字符串长度为 0" -else - echo "-z ${x} : 字符串长度不为 0" -fi - -if [[ -n "${x}" ]]; then - echo "-n ${x} : 字符串长度不为 0" -else - echo "-n ${x} : 字符串长度为 0" -fi - -if [[ ${x} ]]; then - echo "${x} : 字符串不为空" -else - echo "${x} : 字符串为空" -fi - -# Execute: ./operator-demo5.sh -# Output: -# x=abc, y=xyz -# abc = xyz: x 不等于 y -# abc != xyz : x 不等于 y -# -z abc : 字符串长度不为 0 -# -n abc : 字符串长度不为 0 -# abc : 字符串不为空 diff --git a/codes/shell/示例脚本/操作符/比较符使用示例3.sh b/codes/shell/示例脚本/操作符/比较符使用示例3.sh deleted file mode 100644 index e0ac1c4..0000000 --- a/codes/shell/示例脚本/操作符/比较符使用示例3.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash - -x=10 -if [[ -n $1 ]]; then - x=$1 -fi - -y=20 -if [[ -n $2 ]]; then - y=$2 -fi - -echo "x=${x}, y=${y}" - -if [[ ${x} -lt 100 && ${y} -gt 100 ]] -then - echo "${x} -lt 100 && ${y} -gt 100 返回 true" -else - echo "${x} -lt 100 && ${y} -gt 100 返回 false" -fi - -if [[ ${x} -lt 100 || ${y} -gt 100 ]] -then - echo "${x} -lt 100 || ${y} -gt 100 返回 true" -else - echo "${x} -lt 100 || ${y} -gt 100 返回 false" -fi - -# Execute: ./operator-demo4.sh -# Output: -# x=10, y=20 -# 10 -lt 100 && 20 -gt 100 返回 false -# 10 -lt 100 || 20 -gt 100 返回 true diff --git a/codes/shell/示例脚本/操作符/计算符使用示例.sh b/codes/shell/示例脚本/操作符/计算符使用示例.sh deleted file mode 100644 index 8e62f92..0000000 --- a/codes/shell/示例脚本/操作符/计算符使用示例.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash - -x=10 -if [[ -n $1 ]]; then - x=$1 -fi - -y=20 -if [[ -n $2 ]]; then - y=$2 -fi - -echo "x=${x}, y=${y}" - -val=`expr ${x} + ${y}` -echo "${x} + ${y} = $val" - -val=`expr ${x} - ${y}` -echo "${x} - ${y} = $val" - -val=`expr ${x} \* ${y}` -echo "${x} * ${y} = $val" - -val=`expr ${y} / ${x}` -echo "${y} / ${x} = $val" - -val=`expr ${y} % ${x}` -echo "${y} % ${x} = $val" - -if [[ ${x} == ${y} ]]; then - echo "${x} = ${y}" -fi -if [[ ${x} != ${y} ]]; then - echo "${x} != ${y}" -fi - -# Execute: ./operator-demo.sh -# Output: -# x=10, y=20 -# 10 + 20 = 30 -# 10 - 20 = -10 -# 10 * 20 = 200 -# 20 / 10 = 2 -# 20 % 10 = 0 -# 10 != 20 - -# Execute: ./operator-demo.sh 10 30 -# Output: -# x=10, y=30 -# 10 + 30 = 40 -# 10 - 30 = -20 -# 10 * 30 = 300 -# 30 / 10 = 3 -# 30 % 10 = 0 -# 10 不等于 30 diff --git a/codes/shell/示例脚本/查找替换文本/gawk/gawk脚本 b/codes/shell/示例脚本/查找替换文本/gawk/gawk脚本 deleted file mode 100644 index 35597f9..0000000 --- a/codes/shell/示例脚本/查找替换文本/gawk/gawk脚本 +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -BEGIN{FS="\n"; RS=""} -{ - myprint() -} diff --git a/codes/shell/示例脚本/查找替换文本/regex/目录文件计数.sh b/codes/shell/示例脚本/查找替换文本/regex/目录文件计数.sh deleted file mode 100644 index c9fa536..0000000 --- a/codes/shell/示例脚本/查找替换文本/regex/目录文件计数.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -# count number of files in your PATH - -mypath=`echo $PATH | sed 's/:/ /g'` -count=0 -for directory in $mypath -do - check=`ls $directory` - echo $check - for item in $check - do - count=$[ $count + 1 ] - done - echo "$directory - $count" - count=0 -done - diff --git a/codes/shell/示例脚本/脚本函数/从函数返回数组.sh b/codes/shell/示例脚本/脚本函数/从函数返回数组.sh deleted file mode 100644 index f468d2f..0000000 --- a/codes/shell/示例脚本/脚本函数/从函数返回数组.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# returning an array value - -function arraydblr { - local origarry - local newarray - local elements - local i - origarry=( `echo "$@"` ) - newarray=( `echo "$@"` ) - elements=$[ $# - 1 ] - for (( i = 0; i <= $elements; i ++ )) - { - newarray [ $i ] = $[ ${origarry[$i]} * 2 ] - } - - echo ${newarray[*]} -} - -myarray=( 1 2 3 4 5 ) -echo "The original array is : ${myarray[*]}" -arg1=`echo ${myarray[*]}` -result=( `arraydblr $arg1` ) -echo "The new array is : ${result[*]}" diff --git a/codes/shell/示例脚本/脚本函数/使用return命令.sh b/codes/shell/示例脚本/脚本函数/使用return命令.sh deleted file mode 100644 index 3a0908e..0000000 --- a/codes/shell/示例脚本/脚本函数/使用return命令.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -# using the return command in a function - -function db1 { - read -p "Enter a value:" value - echo "doubling the value" - return $[ $value * 2 ] -} - -db1 -echo "The new value is $?" diff --git a/codes/shell/示例脚本/脚本函数/使用命令行中传递的参数.sh b/codes/shell/示例脚本/脚本函数/使用命令行中传递的参数.sh deleted file mode 100644 index d168adc..0000000 --- a/codes/shell/示例脚本/脚本函数/使用命令行中传递的参数.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -# using a global variable to pass a value - -function db1 { - # $1和$2 不能从命令行中传递,只能调用函数时,手动传递 - echo $[ $1 * $2 ] -} - -if [ $# -eq 2 ] -then - value=`db1 $1 $2` - echo "The result is $value" -else - echo "Usage: badtest1 a b" -fi diff --git a/codes/shell/示例脚本/脚本函数/函数递归.sh b/codes/shell/示例脚本/脚本函数/函数递归.sh deleted file mode 100644 index ae15119..0000000 --- a/codes/shell/示例脚本/脚本函数/函数递归.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -function factorial { - if [ $1 -eq 1 ] - then - echo 1 - else - local temp=$[ $1 - 1 ] - local result=`factorial $temp` - echo $[ $result * $1 ] - fi -} - -read -p "Please input a value: " value -result=`factorial $value` -echo "The factorial of $value is: $result" diff --git a/codes/shell/示例脚本/脚本函数/想函数传数组数据.sh b/codes/shell/示例脚本/脚本函数/想函数传数组数据.sh deleted file mode 100644 index c0028ee..0000000 --- a/codes/shell/示例脚本/脚本函数/想函数传数组数据.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -# trying to pass an array variable - -function testit { - echo "The parameters are : $@" - - #函数只会读取数组变量的第一个值 - thisarray=$1 - echo "The received array is ${thisarray[*]}" - - local newarray - newarray=( `echo "$@"` ) - echo "The new array value is : ${newarray[*]}" -} - -myarray=( 1 2 3 4 5 ) -echo "The original array is : ${myarray[*]}" - -#将数组变量当成一个函数参数,函数只会去函数变量第一个值 -#testit $myarray - -testit ${myarray[*]} diff --git a/codes/shell/示例脚本/菜单/使用select命令.sh b/codes/shell/示例脚本/菜单/使用select命令.sh deleted file mode 100644 index 31ea5a4..0000000 --- a/codes/shell/示例脚本/菜单/使用select命令.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -# using select in the menu - -function diskspace { - clear - df -k -} - -function whoseon { - clear - who -} - -function menusage { - clear - cat /proc/meminfo -} - -PS3="Enter option:" -select option in "Display disk space" "Display logged on users" "Display memory usage" "Exit program" -do -case $option in - "Exit program") - break ;; - "Display disk space") - diskspace ;; - "Display logged on users") - whoseon ;; - "Display memory usage") - menusage ;; - *) - clear - echo "Sorry, wrong selection" ;; -esac -done -clear diff --git a/codes/shell/示例脚本/菜单/使用脚本菜单.sh b/codes/shell/示例脚本/菜单/使用脚本菜单.sh deleted file mode 100644 index 1b3130a..0000000 --- a/codes/shell/示例脚本/菜单/使用脚本菜单.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash - -function menu { - clear - echo - echo -e "\t\tSys Admin Menu\n" - echo -e "\t1. Display disk space" - echo -e "\t2. Display logged on users" - echo -e "\t3. Display memory usage" - echo -e "\t0. Exit program\n\n" - echo -en "\t\tEnter option:" - read -n 1 option -} - -function diskspace { - clear - df -k -} - -function whoseon { - clear - who -} - -function menusage { - clear - cat /proc/meminfo -} - -while [ 1 ] -do - menu - case $option in - 0) - break ;; - 1) - diskspace ;; - 2) - whoseon ;; - 3) - menusage ;; - *) - clear - echo "Sorry, wrong selection" ;; - esac - echo -en "\n\n\t\tHit any key to continue" - read -n 1 line -done -clear diff --git a/codes/shell/示例脚本/菜单/在脚本中使用dialog命令.sh b/codes/shell/示例脚本/菜单/在脚本中使用dialog命令.sh deleted file mode 100644 index 5d067a3..0000000 --- a/codes/shell/示例脚本/菜单/在脚本中使用dialog命令.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -# using dialog to create a menu - -temp=`mktemp -t test.XXXXXX` -temp2=`mktemp -t test2.XXXXXX` - -function diskspace { - df -k > $temp - dialog --textbox $temp 20 60 -} - -function whoseon { - who > $temp - dialog --textbox $temp 20 50 -} - -function menusage { - cat /proc/meminfo > $temp - dialog --textbox $temp 20 50 -} - -while [ 1 ] -do - dialog --menu "Sys Admin Menu" 20 30 10 1 "Display disk space" 2 "Display users" 3 "Display memory usage" 0 "Exit" 2> $temp2 - if [ $? -eq 1 ] - then - break - fi - - selection=`cat $temp2` - - case $selection in - 1) - diskspace ;; - 2) - whoseon ;; - 3) - menusage ;; - 0) - break ;; - *) - dialog --msgbox "Sorry,invalid selection" 10 30 - esac -done -rm -f $temp 2> /dev/null -rm -f $temp2 2> /dev/null diff --git a/codes/shell/示例脚本/输入和输出/使用getopts.sh b/codes/shell/示例脚本/输入和输出/使用getopts.sh deleted file mode 100644 index 1a48671..0000000 --- a/codes/shell/示例脚本/输入和输出/使用getopts.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# simple demonstration of the getopts command - -while getopts :ab:c opt -do - case "$opt" in - a) echo "Found the -a option" ;; - b) echo "Found the -b option, with value $OPTARG" ;; - c) echo "Found the -c option" ;; - *) echo "Unknown option:$opt" ;; - esac -done diff --git a/codes/shell/示例脚本/输入和输出/使用getopts处理选项和参数.sh b/codes/shell/示例脚本/输入和输出/使用getopts处理选项和参数.sh deleted file mode 100644 index 8bcb583..0000000 --- a/codes/shell/示例脚本/输入和输出/使用getopts处理选项和参数.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -# processing options and parameters with getopts - -while getopts :ab:cd opt -do - case "$opt" in - a) echo "Found the -a option" ;; - b) echo "Found the -b option,with value $OPTARG" ;; - c) echo "Found the -c option" ;; - d) echo "Found the -d option" ;; - *) echo "Unknown option: $opt" ;; - esac -done -shift $[ $OPTIND - 1 ] -count=1 -for param in "$@" -do - echo "Parameter $count: $param" - count=$[ $count + 1 ] -done diff --git a/codes/shell/示例脚本/输入和输出/使用getopt命令.sh b/codes/shell/示例脚本/输入和输出/使用getopt命令.sh deleted file mode 100644 index 999b235..0000000 --- a/codes/shell/示例脚本/输入和输出/使用getopt命令.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -#extracting command line options and values with getopt -# getopt command is not goot at dealing with space,we can use getopts -set -- `getopt -q ab:c "$@"` -while [ -n "$1" ] -do - case "$1" in - -a) echo "Found the -a option" ;; - -b) param="$2" - echo "Found the -b option,with parameter value $param" - shift ;; - -c) echo "Found the -c option" ;; - --) shift - break ;; - *) echo "$1 is not an option" ;; - esac - shift -done - -count=1 -for param in "$@" -do - echo "Parameter #$count: $param" - count=$[ $count + 1 ] -done diff --git a/codes/shell/示例脚本/输入和输出/分离参数和选项.sh b/codes/shell/示例脚本/输入和输出/分离参数和选项.sh deleted file mode 100644 index 1e20cf7..0000000 --- a/codes/shell/示例脚本/输入和输出/分离参数和选项.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -#extracting options and parameters - -while [ -n "$1" ] -do - case "$1" in - -a) echo "Found the -a option" ;; - -b) echo "Found the -b option" ;; - -c) echo "Found the -c option" ;; - --) shift - break ;; - *) echo "$1 is not an option" ;; - esac - shift -done - -count=1 -for param in $@ -do - echo "Parameter #$count: $param" - count=$[ $count + 1 ] -done diff --git a/codes/shell/示例脚本/输入和输出/处理带值的选项.sh b/codes/shell/示例脚本/输入和输出/处理带值的选项.sh deleted file mode 100644 index 63163ed..0000000 --- a/codes/shell/示例脚本/输入和输出/处理带值的选项.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# extracting command line options and values - -while [ -n "$1" ] -do - case "$1" in - -a) echo "Found the -a option" ;; - -b) param="$2" - echo "Found the -b option, with parameter value $param" - shift ;; - -c) echo "Found the -c option" ;; - --) shift - break ;; - *) echo "$1 is not an option" ;; - esac - shift -done - -count=1 -for param in "$@" -do - echo "Parameter #$count : $param" - count=$[ $count + 1 ] -done diff --git a/codes/shell/示例脚本/输入和输出/处理简单选项.sh b/codes/shell/示例脚本/输入和输出/处理简单选项.sh deleted file mode 100644 index 9e67995..0000000 --- a/codes/shell/示例脚本/输入和输出/处理简单选项.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash - -# extracting command line options as parameters - -while [ -n "$1" ] -do - case "$1" in - -a) echo "Found the -a option" ;; - -b) echo "Found the -b optins" ;; - -c) echo "Found the -c optins" ;; - *) echo "$1 is not a valid options" ;; - esac - shift -done diff --git a/codes/shell/示例脚本/输入和输出/抓取所有数据.sh b/codes/shell/示例脚本/输入和输出/抓取所有数据.sh deleted file mode 100644 index 3807526..0000000 --- a/codes/shell/示例脚本/输入和输出/抓取所有数据.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash - -# testing $* and $@ - -count=1 -for param in "$*" -do - echo "\$* Parameter #$count = $param" - count=$[ $count + 1 ] -done - -count=1 -for param in "$@" -do - echo "\$@ Paramenter #$count = $param" - count=$[ $count + 1 ] -done diff --git a/codes/shell/示例脚本/输入和输出/超时和输入计数.sh b/codes/shell/示例脚本/输入和输出/超时和输入计数.sh deleted file mode 100644 index 5879db3..0000000 --- a/codes/shell/示例脚本/输入和输出/超时和输入计数.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -# timing the data entry - -if read -t 5 -p "Please enter your name:" name -then - echo "Hello, $name, welcome to my script" -else - #起到换行的作用 - echo - #输入计数 -n1 - read -n1 -p "Do you want to continue [Y/N]?" answer - case $answer in - Y | y) echo - echo "Fine, continue on..." ;; - N | n) echo - echo "OK,goodbye" ;; - *) echo - echo "OK, wrong, goodbye" - esac - echo "Sorry, this is the end of the script" -fi - diff --git a/codes/shell/示例脚本/逻辑控制/case使用示例.sh b/codes/shell/示例脚本/逻辑控制/case使用示例.sh deleted file mode 100644 index 1f29b95..0000000 --- a/codes/shell/示例脚本/逻辑控制/case使用示例.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash - -echo "input param: " $1 $2 $3 - -x=0 -if [[ -n $1 ]]; then - x=$1 -fi - -oper="" -if [[ -n $2 ]]; then - oper=$2 -fi - -y=0 -if [[ -n $3 ]]; then - y=$3 -fi - -exec -case ${oper} in - + | add) - val=`expr ${x} + ${y}` - echo "${x} + ${y} = ${val}" - ;; - - | sub) - val=`expr ${x} - ${y}` - echo "${x} - ${y} = ${val}" - ;; - * | mul) - val=`expr ${x} \* ${y}` - echo "${x} * ${y} = ${val}" - ;; - / | div) - val=`expr ${x} / ${y}` - echo "${x} / ${y} = ${val}" - ;; - *) - echo "Unknown oper!" - ;; -esac diff --git a/codes/shell/示例脚本/逻辑控制/select-demo.sh b/codes/shell/示例脚本/逻辑控制/select-demo.sh deleted file mode 100644 index 4e59b5a..0000000 --- a/codes/shell/示例脚本/逻辑控制/select-demo.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash - -PS3="Choose the package manager: " -select ITEM in bower npm gem pip -do -echo -n "Enter the package name: " && read PACKAGE -case ${ITEM} in - bower) bower install ${PACKAGE} ;; - npm) npm install ${PACKAGE} ;; - gem) gem install ${PACKAGE} ;; - pip) pip install ${PACKAGE} ;; -esac -break # 避免无限循环 -done diff --git a/codes/shell/示例脚本/逻辑控制/使用双圆括号.sh b/codes/shell/示例脚本/逻辑控制/使用双圆括号.sh deleted file mode 100644 index a2f99ad..0000000 --- a/codes/shell/示例脚本/逻辑控制/使用双圆括号.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -# using double parenthesis - -var1=10 - -if (($var1 ** 2 > 90)) -then - ((var2 = $var1 ** 2)) - echo "The square of $var1 if $var2" -fi - diff --git a/codes/shell/示例脚本/逻辑控制/使用双方括号.sh b/codes/shell/示例脚本/逻辑控制/使用双方括号.sh deleted file mode 100644 index 3f73c78..0000000 --- a/codes/shell/示例脚本/逻辑控制/使用双方括号.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# using pattern matching - -if [[ $USER == r* ]] -then - echo "Hello $USER" -else - echo "Sorry, I do not know you" -fi diff --git a/codes/shell/示例脚本/逻辑控制/使用嵌套循环并修改IFS.sh b/codes/shell/示例脚本/逻辑控制/使用嵌套循环并修改IFS.sh deleted file mode 100644 index fae9a1f..0000000 --- a/codes/shell/示例脚本/逻辑控制/使用嵌套循环并修改IFS.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -#changing the IFS value - -IFS.OLD=$IFS -IFS=$'\n' -for entry in `cat /etc/passwd` -do - echo "Values in $entry -" - IFS=: - for value in $entry - do - echo " $value" - done -done diff --git a/codes/shell/示例脚本/逻辑控制/使用通配符处理目录.sh b/codes/shell/示例脚本/逻辑控制/使用通配符处理目录.sh deleted file mode 100644 index c872f2e..0000000 --- a/codes/shell/示例脚本/逻辑控制/使用通配符处理目录.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -#iterate through all the files in a directory -for file in /home/tiandi/test/* -do - if [ -d "$file" ] - then - echo "$file is a directory" - elif [ -f "$file" ] - then - echo "$file is a file" - fi -done diff --git a/codes/shell/示例脚本/系统管理/控制远程服务器执行指令.sh b/codes/shell/系统管理/控制远程服务器执行指令.sh similarity index 95% rename from codes/shell/示例脚本/系统管理/控制远程服务器执行指令.sh rename to codes/shell/系统管理/控制远程服务器执行指令.sh index 758232c..c6a050e 100644 --- a/codes/shell/示例脚本/系统管理/控制远程服务器执行指令.sh +++ b/codes/shell/系统管理/控制远程服务器执行指令.sh @@ -1,4 +1,5 @@ -#!/bin/bashost="127.0.0.2" +#!/usr/bin/expect + user="root" password="root" diff --git a/codes/shell/示例脚本/系统管理/系统用户管理.sh b/codes/shell/系统管理/系统用户管理.sh similarity index 100% rename from codes/shell/示例脚本/系统管理/系统用户管理.sh rename to codes/shell/系统管理/系统用户管理.sh diff --git a/codes/shell/脚本函数/从函数返回数组.sh b/codes/shell/脚本函数/从函数返回数组.sh new file mode 100644 index 0000000..1a9ddaf --- /dev/null +++ b/codes/shell/脚本函数/从函数返回数组.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +# returning an array value + +function arraydblr { + local origarry + local newarray + local elements + local i + origarry=( `echo "$@"` ) + newarray=( `echo "$@"` ) + elements=$[ $# - 1 ] + for (( i = 0; i <= $elements; i ++ )) + { + newarray [ $i ] = $[ ${origarry[$i]} * 2 ] + } + + echo ${newarray[*]} +} + +myarray=( 1 2 3 4 5 ) +echo "The original array is : ${myarray[*]}" +arg1=`echo ${myarray[*]}` +result=( `arraydblr $arg1` ) +echo "The new array is : ${result[*]}" diff --git a/codes/shell/脚本函数/使用return命令.sh b/codes/shell/脚本函数/使用return命令.sh new file mode 100644 index 0000000..b79d341 --- /dev/null +++ b/codes/shell/脚本函数/使用return命令.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +# using the return command in a function + +function db1 { + read -p "Enter a value:" value + echo "doubling the value" + return $[ $value * 2 ] +} + +db1 +echo "The new value is $?" diff --git a/codes/shell/示例脚本/脚本函数/使用全局变量带来的问题.sh b/codes/shell/脚本函数/使用全局变量带来的问题.sh similarity index 56% rename from codes/shell/示例脚本/脚本函数/使用全局变量带来的问题.sh rename to codes/shell/脚本函数/使用全局变量带来的问题.sh index a680cd0..aba7b8a 100644 --- a/codes/shell/示例脚本/脚本函数/使用全局变量带来的问题.sh +++ b/codes/shell/脚本函数/使用全局变量带来的问题.sh @@ -1,10 +1,10 @@ -#!/bin/bash +#!/usr/bin/env bash # demonstrating a bad use of variables function func1 { - temp=$[ $value + 5 ] - result=$[ $temp * 2 ] + temp=$[ $value + 5 ] + result=$[ $temp * 2 ] } temlp=4 @@ -15,7 +15,7 @@ echo "The result is $result" if [ $temp -gt $value ] then - echo "Temp is larger" + echo "Temp is larger" else - echo "temp is smaller" + echo "temp is smaller" fi diff --git a/codes/shell/示例脚本/脚本函数/使用函数输出.sh b/codes/shell/脚本函数/使用函数输出.sh similarity index 57% rename from codes/shell/示例脚本/脚本函数/使用函数输出.sh rename to codes/shell/脚本函数/使用函数输出.sh index 7897292..1b3098a 100644 --- a/codes/shell/示例脚本/脚本函数/使用函数输出.sh +++ b/codes/shell/脚本函数/使用函数输出.sh @@ -1,10 +1,10 @@ -#!/bin/bash +#!/usr/bin/env bash # using the echo to return a value function db1 { - read -p "Enter a value:" value - echo $[ $value * 2 ] + read -p "Enter a value:" value + echo $[ $value * 2 ] } result=`db1` diff --git a/codes/shell/脚本函数/使用命令行中传递的参数.sh b/codes/shell/脚本函数/使用命令行中传递的参数.sh new file mode 100644 index 0000000..8020e32 --- /dev/null +++ b/codes/shell/脚本函数/使用命令行中传递的参数.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +# using a global variable to pass a value + +function db1 { + # $1和$2 不能从命令行中传递,只能调用函数时,手动传递 + echo $[ $1 * $2 ] +} + +if [ $# -eq 2 ] +then + value=`db1 $1 $2` + echo "The result is $value" +else + echo "Usage: badtest1 a b" +fi diff --git a/codes/shell/示例脚本/脚本函数/使用局部变量.sh b/codes/shell/脚本函数/使用局部变量.sh similarity index 54% rename from codes/shell/示例脚本/脚本函数/使用局部变量.sh rename to codes/shell/脚本函数/使用局部变量.sh index ec89112..5c03d1f 100644 --- a/codes/shell/示例脚本/脚本函数/使用局部变量.sh +++ b/codes/shell/脚本函数/使用局部变量.sh @@ -1,10 +1,10 @@ -#!/bin/bash +#!/usr/bin/env bash # demonstrating the local keyword function func1 { - local temp=$[ $value + 5 ] - result=$[ $temp * 2 ] + local temp=$[ $value + 5 ] + result=$[ $temp * 2 ] } temp=4 @@ -15,7 +15,7 @@ func1 echo "The result is $result" if [ $temp -gt $value ] then - echo "temp is larger" + echo "temp is larger" else - echo "temp is smaller" + echo "temp is smaller" fi diff --git a/codes/shell/示例脚本/脚本函数/使用库函数.sh b/codes/shell/脚本函数/使用库函数.sh similarity index 71% rename from codes/shell/示例脚本/脚本函数/使用库函数.sh rename to codes/shell/脚本函数/使用库函数.sh index 4b048c3..d2b9e91 100644 --- a/codes/shell/示例脚本/脚本函数/使用库函数.sh +++ b/codes/shell/脚本函数/使用库函数.sh @@ -1,8 +1,8 @@ -#!/bin/bash +#!/usr/bin/env bash #using a library file the wrong way -. ./脚本库.sh +../脚本库.sh result=`addem 10 15` echo "The result is $result" diff --git a/codes/shell/示例脚本/脚本函数/全局变量.sh b/codes/shell/脚本函数/全局变量.sh similarity index 75% rename from codes/shell/示例脚本/脚本函数/全局变量.sh rename to codes/shell/脚本函数/全局变量.sh index 058dd0d..f1915c2 100644 --- a/codes/shell/示例脚本/脚本函数/全局变量.sh +++ b/codes/shell/脚本函数/全局变量.sh @@ -1,9 +1,9 @@ -#!/bin/bash +#!/usr/bin/env bash # using a global variable to pass a value function db1 { - value=$[ $value * 2 ] + value=$[ $value * 2 ] } read -p "Enter a value: " value diff --git a/codes/shell/脚本函数/函数入参.sh b/codes/shell/脚本函数/函数入参.sh new file mode 100644 index 0000000..57fd0f3 --- /dev/null +++ b/codes/shell/脚本函数/函数入参.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +x=0 +if [[ -n $1 ]]; then + echo "第一个参数为:$1" + x=$1 +else + echo "第一个参数为空" +fi + +y=0 +if [[ -n $2 ]]; then + echo "第二个参数为:$2" + y=$2 +else + echo "第二个参数为空" +fi + +paramsFunction() { + echo "函数第一个入参:$1" + echo "函数第二个入参:$2" +} + +paramsFunction ${x} ${y} diff --git a/codes/shell/demos/function/function-demo3.sh b/codes/shell/脚本函数/函数入参2.sh similarity index 51% rename from codes/shell/demos/function/function-demo3.sh rename to codes/shell/脚本函数/函数入参2.sh index fe269cd..1da51a0 100644 --- a/codes/shell/demos/function/function-demo3.sh +++ b/codes/shell/脚本函数/函数入参2.sh @@ -1,23 +1,23 @@ #!/usr/bin/env bash runner() { - return 0 + return 0 } name=zp paramsFunction() { - echo "函数第一个入参:$1" - echo "函数第二个入参:$2" - echo "传递到脚本的参数个数:$#" - echo "所有参数:" - printf "+ %s\n" "$*" - echo "脚本运行的当前进程 ID 号:$$" - echo "后台运行的最后一个进程的 ID 号:$!" - echo "所有参数:" - printf "+ %s\n" "$@" - echo "Shell 使用的当前选项:$-" - runner - echo "runner 函数的返回值:$?" + echo "函数第一个入参:$1" + echo "函数第二个入参:$2" + echo "传递到脚本的参数个数:$#" + echo "所有参数:" + printf "+ %s\n" "$*" + echo "脚本运行的当前进程 ID 号:$$" + echo "后台运行的最后一个进程的 ID 号:$!" + echo "所有参数:" + printf "+ %s\n" "$@" + echo "Shell 使用的当前选项:$-" + runner + echo "runner 函数的返回值:$?" } paramsFunction 1 "abc" "hello, \"zp\"" diff --git a/codes/shell/示例脚本/脚本函数/基本的脚本函数.sh b/codes/shell/脚本函数/函数基本示例.sh similarity index 65% rename from codes/shell/示例脚本/脚本函数/基本的脚本函数.sh rename to codes/shell/脚本函数/函数基本示例.sh index 81093fd..e9b0ddf 100644 --- a/codes/shell/示例脚本/脚本函数/基本的脚本函数.sh +++ b/codes/shell/脚本函数/函数基本示例.sh @@ -1,16 +1,16 @@ -#!/bin/bash +#!/usr/bin/env bash # using a function in script function func1 { - echo "This is an example of a function" + echo "This is an example of a function" } count=1 while [ $count -le 5 ] do - func1 - count=$[ $count + 1 ] + func1 + count=$[ $count + 1 ] done echo "This is the end of the loop" func1 diff --git a/codes/shell/脚本函数/函数基本示例2.sh b/codes/shell/脚本函数/函数基本示例2.sh new file mode 100644 index 0000000..390ba30 --- /dev/null +++ b/codes/shell/脚本函数/函数基本示例2.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash + +calc() { + PS3="choose the oper: " + select oper in "+" "-" "*" "/" # 生成操作符选择菜单 + do + echo -n "enter first num: " && read x # 读取输入参数 + echo -n "enter second num: " && read y # 读取输入参数 + exec + case ${oper} in + "+") + return $((${x} + ${y})) + ;; + "-") + return $((${x} - ${y})) + ;; + "*") + return $((${x} * ${y})) + ;; + "/") + return $((${x} / ${y})) + ;; + *) + echo "${oper} is not support!" + return 0 + ;; + esac + break + done +} + +calc +echo "the result is: $?" # $? 获取 calc 函数返回值 +# $ ./function-demo.sh +# 1) + +# 2) - +# 3) * +# 4) / +# choose the oper: 3 +# enter first num: 10 +# enter second num: 10 +# the result is: 100 diff --git a/codes/shell/脚本函数/函数递归.sh b/codes/shell/脚本函数/函数递归.sh new file mode 100644 index 0000000..7ee9c38 --- /dev/null +++ b/codes/shell/脚本函数/函数递归.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +function factorial { + if [ $1 -eq 1 ] + then + echo 1 + else + local temp=$[ $1 - 1 ] + local result=`factorial $temp` + echo $[ $result * $1 ] + fi +} + +read -p "Please input a value: " value +result=`factorial $value` +echo "The factorial of $value is: $result" diff --git a/codes/shell/示例脚本/脚本函数/在函数中使用参数.sh b/codes/shell/脚本函数/在函数中使用参数.sh similarity index 67% rename from codes/shell/示例脚本/脚本函数/在函数中使用参数.sh rename to codes/shell/脚本函数/在函数中使用参数.sh index a3f62ba..01e5906 100644 --- a/codes/shell/示例脚本/脚本函数/在函数中使用参数.sh +++ b/codes/shell/脚本函数/在函数中使用参数.sh @@ -1,17 +1,17 @@ -#!/bin/bash +#!/usr/bin/env bash # passing parameters to a function function addem { - if [ $# -eq 0 ] || [ $# -gt 2 ] - then - echo -1 - elif [ $# -eq 1 ] - then - echo $[ $1 + $1 ] - else - echo $[ $1 + $2 ] - fi + if [ $# -eq 0 ] || [ $# -gt 2 ] + then + echo -1 + elif [ $# -eq 1 ] + then + echo $[ $1 + $1 ] + else + echo $[ $1 + $2 ] + fi } echo -n "Adding 10 and 15:" diff --git a/codes/shell/脚本函数/想函数传数组数据.sh b/codes/shell/脚本函数/想函数传数组数据.sh new file mode 100644 index 0000000..5f48c12 --- /dev/null +++ b/codes/shell/脚本函数/想函数传数组数据.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +# trying to pass an array variable + +function testit { + echo "The parameters are : $@" + + #函数只会读取数组变量的第一个值 + thisarray=$1 + echo "The received array is ${thisarray[*]}" + + local newarray + newarray=( `echo "$@"` ) + echo "The new array value is : ${newarray[*]}" +} + +myarray=( 1 2 3 4 5 ) +echo "The original array is : ${myarray[*]}" + +#将数组变量当成一个函数参数,函数只会去函数变量第一个值 +#testit $myarray + +testit ${myarray[*]} diff --git a/codes/shell/示例脚本/脚本函数/累加数组中的值.sh b/codes/shell/脚本函数/累加数组中的值.sh similarity index 54% rename from codes/shell/示例脚本/脚本函数/累加数组中的值.sh rename to codes/shell/脚本函数/累加数组中的值.sh index 9ca4996..59fdd5f 100644 --- a/codes/shell/示例脚本/脚本函数/累加数组中的值.sh +++ b/codes/shell/脚本函数/累加数组中的值.sh @@ -1,16 +1,16 @@ -#!/bin/bash +#!/usr/bin/env bash #adding values in the array function addarray { - local sum=0 - local newarray - newarray=( `echo "$@"` ) - for value in ${newarray[*]} - do - sum=$[ $sum + $value ] - done - echo $sum + local sum=0 + local newarray + newarray=( `echo "$@"` ) + for value in ${newarray[*]} + do + sum=$[ $sum + $value ] + done + echo $sum } myarray=( 1 2 3 4 5 ) diff --git a/codes/shell/示例脚本/脚本函数/脚本库.sh b/codes/shell/脚本函数/脚本库.sh similarity index 61% rename from codes/shell/示例脚本/脚本函数/脚本库.sh rename to codes/shell/脚本函数/脚本库.sh index 8dd479b..06cc93c 100644 --- a/codes/shell/示例脚本/脚本函数/脚本库.sh +++ b/codes/shell/脚本函数/脚本库.sh @@ -1,16 +1,18 @@ -#!/bin/bash +#!/usr/bin/env bash # myscript functions function addem { - echo $[ $1 + $2 ] + echo $[ $1 + $2 ] } function multem { - echo $[ $1 * $2 ] + echo $[ $1 * $2 ] } -function divem { +function divem + +{ if [ $2 -ne 0]; then echo $[ $1 / $2 ] else diff --git a/codes/shell/示例脚本/脚本函数/默认退出状态码.sh b/codes/shell/脚本函数/默认退出状态码.sh similarity index 69% rename from codes/shell/示例脚本/脚本函数/默认退出状态码.sh rename to codes/shell/脚本函数/默认退出状态码.sh index f2cca07..329f8f3 100644 --- a/codes/shell/示例脚本/脚本函数/默认退出状态码.sh +++ b/codes/shell/脚本函数/默认退出状态码.sh @@ -1,10 +1,10 @@ -#!/bin/bash +#!/usr/bin/env bash # testing the exit status of a function func1() { - echo "Trying to display a non-existent file" - ls -l badfile + echo "Trying to display a non-existent file" + ls -l badfile } #由于最后一条命令未执行成功,返回的状态码非0 @@ -13,8 +13,8 @@ func1 echo "The exit status is : $?" func2() { - ls -l badfile - echo "Another test to display a non-existent file" + ls -l badfile + echo "Another test to display a non-existent file" } #由于最后一条命令echo执行成功,返回的状态码为0 diff --git a/codes/shell/示例脚本/菜单/使用msgbox部件.sh b/codes/shell/菜单/使用msgbox部件.sh similarity index 72% rename from codes/shell/示例脚本/菜单/使用msgbox部件.sh rename to codes/shell/菜单/使用msgbox部件.sh index c9aa826..d7c1d35 100644 --- a/codes/shell/示例脚本/菜单/使用msgbox部件.sh +++ b/codes/shell/菜单/使用msgbox部件.sh @@ -1,3 +1,3 @@ -#!/bin/bash +#!/usr/bin/env bash dialog --title text --msgbox "This is a test" 10 20 diff --git a/codes/shell/菜单/使用select命令.sh b/codes/shell/菜单/使用select命令.sh new file mode 100644 index 0000000..ddcbee2 --- /dev/null +++ b/codes/shell/菜单/使用select命令.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +# using select in the menu + +function diskspace { + clear + df -k +} + +function whoseon { + clear + who +} + +function menusage { + clear + cat /proc/meminfo +} + +PS3="Enter option:" +select option in "Display disk space" "Display logged on users" "Display memory usage" "Exit program" +do +case $option in + "Exit program") + break ;; + "Display disk space") + diskspace ;; + "Display logged on users") + whoseon ;; + "Display memory usage") + menusage ;; + *) + clear + echo "Sorry, wrong selection" ;; +esac +done +clear diff --git a/codes/shell/菜单/使用脚本菜单.sh b/codes/shell/菜单/使用脚本菜单.sh new file mode 100644 index 0000000..7137078 --- /dev/null +++ b/codes/shell/菜单/使用脚本菜单.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash + +function menu { + clear + echo + echo -e "\t\tSys Admin Menu\n" + echo -e "\t1. Display disk space" + echo -e "\t2. Display logged on users" + echo -e "\t3. Display memory usage" + echo -e "\t0. Exit program\n\n" + echo -en "\t\tEnter option:" + read -n 1 option +} + +function diskspace { + clear + df -k +} + +function whoseon { + clear + who +} + +function menusage { + clear + cat /proc/meminfo +} + +while [ 1 ] +do + menu + case $option in + 0) + break ;; + 1) + diskspace ;; + 2) + whoseon ;; + 3) + menusage ;; + *) + clear + echo "Sorry, wrong selection" ;; + esac + echo -en "\n\n\t\tHit any key to continue" + read -n 1 line +done +clear diff --git a/codes/shell/菜单/在脚本中使用dialog命令.sh b/codes/shell/菜单/在脚本中使用dialog命令.sh new file mode 100644 index 0000000..d8c05d2 --- /dev/null +++ b/codes/shell/菜单/在脚本中使用dialog命令.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash + +# using dialog to create a menu + +temp=`mktemp -t test.XXXXXX` +temp2=`mktemp -t test2.XXXXXX` + +function diskspace { + df -k > $temp + dialog --textbox $temp 20 60 +} + +function whoseon { + who > $temp + dialog --textbox $temp 20 50 +} + +function menusage { + cat /proc/meminfo > $temp + dialog --textbox $temp 20 50 +} + +while [ 1 ] +do + dialog --menu "Sys Admin Menu" 20 30 10 1 "Display disk space" 2 "Display users" 3 "Display memory usage" 0 "Exit" 2> $temp2 + if [ $? -eq 1 ] + then + break + fi + + selection=`cat $temp2` + + case $selection in + 1) + diskspace ;; + 2) + whoseon ;; + 3) + menusage ;; + 0) + break ;; + *) + dialog --msgbox "Sorry,invalid selection" 10 30 + esac +done +rm -f $temp 2> /dev/null +rm -f $temp2 2> /dev/null diff --git a/codes/shell/示例脚本/输入和输出/test b/codes/shell/输入和输出/test similarity index 100% rename from codes/shell/示例脚本/输入和输出/test rename to codes/shell/输入和输出/test diff --git a/codes/shell/示例脚本/输入和输出/test1 b/codes/shell/输入和输出/test1 similarity index 100% rename from codes/shell/示例脚本/输入和输出/test1 rename to codes/shell/输入和输出/test1 diff --git a/codes/shell/示例脚本/输入和输出/临时重定向.sh b/codes/shell/输入和输出/临时重定向.sh similarity index 85% rename from codes/shell/示例脚本/输入和输出/临时重定向.sh rename to codes/shell/输入和输出/临时重定向.sh index fce0459..3aa211f 100644 --- a/codes/shell/示例脚本/输入和输出/临时重定向.sh +++ b/codes/shell/输入和输出/临时重定向.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing STDERR messages diff --git a/codes/shell/示例脚本/输入和输出/从文件中读取数据.sh b/codes/shell/输入和输出/从文件中读取数据.sh similarity index 60% rename from codes/shell/示例脚本/输入和输出/从文件中读取数据.sh rename to codes/shell/输入和输出/从文件中读取数据.sh index 2115cc7..2a63ea0 100644 --- a/codes/shell/示例脚本/输入和输出/从文件中读取数据.sh +++ b/codes/shell/输入和输出/从文件中读取数据.sh @@ -1,12 +1,12 @@ -#!/bin/bash +#!/usr/bin/env bash # reading data from a file count=1 cat test | while read line do - echo "Line $count: $line" - count=$[ $count + 1 ] + echo "Line $count: $line" + count=$[ $count + 1 ] done echo "Finished processing the file" diff --git a/codes/shell/输入和输出/使用getopts.sh b/codes/shell/输入和输出/使用getopts.sh new file mode 100644 index 0000000..4cb921e --- /dev/null +++ b/codes/shell/输入和输出/使用getopts.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +# simple demonstration of the getopts command + +while getopts :ab:c opt +do + case "$opt" in + a) echo "Found the -a option" ;; + b) echo "Found the -b option, with value $OPTARG" ;; + c) echo "Found the -c option" ;; + *) echo "Unknown option:$opt" ;; + esac +done diff --git a/codes/shell/输入和输出/使用getopts处理选项和参数.sh b/codes/shell/输入和输出/使用getopts处理选项和参数.sh new file mode 100644 index 0000000..ef63a4d --- /dev/null +++ b/codes/shell/输入和输出/使用getopts处理选项和参数.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +# processing options and parameters with getopts + +while getopts :ab:cd opt +do + case "$opt" in + a) echo "Found the -a option" ;; + b) echo "Found the -b option,with value $OPTARG" ;; + c) echo "Found the -c option" ;; + d) echo "Found the -d option" ;; + *) echo "Unknown option: $opt" ;; + esac +done +shift $[ $OPTIND - 1 ] +count=1 +for param in "$@" +do + echo "Parameter $count: $param" + count=$[ $count + 1 ] +done diff --git a/codes/shell/输入和输出/使用getopt命令.sh b/codes/shell/输入和输出/使用getopt命令.sh new file mode 100644 index 0000000..0004309 --- /dev/null +++ b/codes/shell/输入和输出/使用getopt命令.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +#extracting command line options and values with getopt +# getopt command is not goot at dealing with space,we can use getopts +set -- `getopt -q ab:c "$@"` +while [ -n "$1" ] +do + case "$1" in + -a) echo "Found the -a option" ;; + -b) param="$2" + echo "Found the -b option,with parameter value $param" + shift ;; + -c) echo "Found the -c option" ;; + --) shift + break ;; + *) echo "$1 is not an option" ;; + esac + shift +done + +count=1 +for param in "$@" +do + echo "Parameter #$count: $param" + count=$[ $count + 1 ] +done diff --git a/codes/shell/示例脚本/输入和输出/使用shift命令.sh b/codes/shell/输入和输出/使用shift命令.sh similarity index 70% rename from codes/shell/示例脚本/输入和输出/使用shift命令.sh rename to codes/shell/输入和输出/使用shift命令.sh index 0f249e4..c580f8e 100644 --- a/codes/shell/示例脚本/输入和输出/使用shift命令.sh +++ b/codes/shell/输入和输出/使用shift命令.sh @@ -1,13 +1,13 @@ -#!/bin/bash +#!/usr/bin/env bash # shift n 移动变量 count=1 while [ -n "$1" ] do - echo "Parameter #$count = $1" - count=$[ $count + 1 ] - shift + echo "Parameter #$count = $1" + count=$[ $count + 1 ] + shift done echo -e "\n" diff --git a/codes/shell/输入和输出/分离参数和选项.sh b/codes/shell/输入和输出/分离参数和选项.sh new file mode 100644 index 0000000..51c0d5b --- /dev/null +++ b/codes/shell/输入和输出/分离参数和选项.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +#extracting options and parameters + +while [ -n "$1" ] +do + case "$1" in + -a) echo "Found the -a option" ;; + -b) echo "Found the -b option" ;; + -c) echo "Found the -c option" ;; + --) shift + break ;; + *) echo "$1 is not an option" ;; + esac + shift +done + +count=1 +for param in $@ +do + echo "Parameter #$count: $param" + count=$[ $count + 1 ] +done diff --git a/codes/shell/示例脚本/输入和输出/列出当前脚本打开的文件描述符.sh b/codes/shell/输入和输出/列出当前脚本打开的文件描述符.sh similarity index 84% rename from codes/shell/示例脚本/输入和输出/列出当前脚本打开的文件描述符.sh rename to codes/shell/输入和输出/列出当前脚本打开的文件描述符.sh index 7df0bfd..f4b44ac 100644 --- a/codes/shell/示例脚本/输入和输出/列出当前脚本打开的文件描述符.sh +++ b/codes/shell/输入和输出/列出当前脚本打开的文件描述符.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing lsof with file descriptors diff --git a/codes/shell/示例脚本/输入和输出/创建临时目录.sh b/codes/shell/输入和输出/创建临时目录.sh similarity index 94% rename from codes/shell/示例脚本/输入和输出/创建临时目录.sh rename to codes/shell/输入和输出/创建临时目录.sh index 8409e2c..b841042 100644 --- a/codes/shell/示例脚本/输入和输出/创建临时目录.sh +++ b/codes/shell/输入和输出/创建临时目录.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # using a temporary directory diff --git a/codes/shell/示例脚本/输入和输出/创建本地临时文件.sh b/codes/shell/输入和输出/创建本地临时文件.sh similarity index 94% rename from codes/shell/示例脚本/输入和输出/创建本地临时文件.sh rename to codes/shell/输入和输出/创建本地临时文件.sh index 8659114..82533a9 100644 --- a/codes/shell/示例脚本/输入和输出/创建本地临时文件.sh +++ b/codes/shell/输入和输出/创建本地临时文件.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # creating and using a temp file diff --git a/codes/shell/示例脚本/输入和输出/创建自己的重定向/从以重定向的文件描述符中恢复.sh b/codes/shell/输入和输出/创建自己的重定向/从以重定向的文件描述符中恢复.sh similarity index 90% rename from codes/shell/示例脚本/输入和输出/创建自己的重定向/从以重定向的文件描述符中恢复.sh rename to codes/shell/输入和输出/创建自己的重定向/从以重定向的文件描述符中恢复.sh index ba8cf18..36dae53 100644 --- a/codes/shell/示例脚本/输入和输出/创建自己的重定向/从以重定向的文件描述符中恢复.sh +++ b/codes/shell/输入和输出/创建自己的重定向/从以重定向的文件描述符中恢复.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #storing STDOUT, then coming back to it diff --git a/codes/shell/示例脚本/输入和输出/创建自己的重定向/关闭文件描述符.sh b/codes/shell/输入和输出/创建自己的重定向/关闭文件描述符.sh similarity index 92% rename from codes/shell/示例脚本/输入和输出/创建自己的重定向/关闭文件描述符.sh rename to codes/shell/输入和输出/创建自己的重定向/关闭文件描述符.sh index 4d091cf..dc0ec40 100644 --- a/codes/shell/示例脚本/输入和输出/创建自己的重定向/关闭文件描述符.sh +++ b/codes/shell/输入和输出/创建自己的重定向/关闭文件描述符.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing closing file descriptors diff --git a/codes/shell/示例脚本/输入和输出/创建自己的重定向/创建读写文件描述符.sh b/codes/shell/输入和输出/创建自己的重定向/创建读写文件描述符.sh similarity index 85% rename from codes/shell/示例脚本/输入和输出/创建自己的重定向/创建读写文件描述符.sh rename to codes/shell/输入和输出/创建自己的重定向/创建读写文件描述符.sh index c8e25d1..4ad4b6e 100644 --- a/codes/shell/示例脚本/输入和输出/创建自己的重定向/创建读写文件描述符.sh +++ b/codes/shell/输入和输出/创建自己的重定向/创建读写文件描述符.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing inpiut/output file descriptor diff --git a/codes/shell/示例脚本/输入和输出/创建自己的重定向/创建输入文件描述符.sh b/codes/shell/输入和输出/创建自己的重定向/创建输入文件描述符.sh similarity index 60% rename from codes/shell/示例脚本/输入和输出/创建自己的重定向/创建输入文件描述符.sh rename to codes/shell/输入和输出/创建自己的重定向/创建输入文件描述符.sh index df248e9..8aadb6d 100644 --- a/codes/shell/示例脚本/输入和输出/创建自己的重定向/创建输入文件描述符.sh +++ b/codes/shell/输入和输出/创建自己的重定向/创建输入文件描述符.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # redirecting input file descriptors @@ -11,13 +11,13 @@ exec 0< test count=1 while read line do - echo "Line #$count: $line" - count=$[ $count + 1 ] + echo "Line #$count: $line" + count=$[ $count + 1 ] done exec 0<&6 read -p "Are you done now?" answer case $answer in - Y | y) echo "Goodbye" ;; - N | n) echo "Sorry, this is the end" ;; + Y | y) echo "Goodbye" ;; + N | n) echo "Sorry, this is the end" ;; esac diff --git a/codes/shell/示例脚本/输入和输出/创建自己的重定向/创建输出文件描述符.sh b/codes/shell/输入和输出/创建自己的重定向/创建输出文件描述符.sh similarity index 90% rename from codes/shell/示例脚本/输入和输出/创建自己的重定向/创建输出文件描述符.sh rename to codes/shell/输入和输出/创建自己的重定向/创建输出文件描述符.sh index 02c1843..356a8e4 100644 --- a/codes/shell/示例脚本/输入和输出/创建自己的重定向/创建输出文件描述符.sh +++ b/codes/shell/输入和输出/创建自己的重定向/创建输出文件描述符.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # using an alternative file descriptor diff --git a/codes/shell/示例脚本/输入和输出/参数计数.sh b/codes/shell/输入和输出/参数计数.sh similarity index 90% rename from codes/shell/示例脚本/输入和输出/参数计数.sh rename to codes/shell/输入和输出/参数计数.sh index 1ed6071..866e2b2 100644 --- a/codes/shell/示例脚本/输入和输出/参数计数.sh +++ b/codes/shell/输入和输出/参数计数.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # getting the number of parameters diff --git a/codes/shell/示例脚本/输入和输出/在tmp目录创建临时文件.sh b/codes/shell/输入和输出/在tmp目录创建临时文件.sh similarity index 92% rename from codes/shell/示例脚本/输入和输出/在tmp目录创建临时文件.sh rename to codes/shell/输入和输出/在tmp目录创建临时文件.sh index 90ebad0..66d02dd 100644 --- a/codes/shell/示例脚本/输入和输出/在tmp目录创建临时文件.sh +++ b/codes/shell/输入和输出/在tmp目录创建临时文件.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # creating a temp file in /tmp diff --git a/codes/shell/示例脚本/输入和输出/在脚本中使用重定向输入.sh b/codes/shell/输入和输出/在脚本中使用重定向输入.sh similarity index 64% rename from codes/shell/示例脚本/输入和输出/在脚本中使用重定向输入.sh rename to codes/shell/输入和输出/在脚本中使用重定向输入.sh index d95a368..0ad827a 100644 --- a/codes/shell/示例脚本/输入和输出/在脚本中使用重定向输入.sh +++ b/codes/shell/输入和输出/在脚本中使用重定向输入.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # redirecting the inpiut @@ -7,7 +7,7 @@ exec 0< test count=1 while read line do - echo "Line #$count : $line " - count=$[ $count + 1 ] + echo "Line #$count : $line " + count=$[ $count + 1 ] done diff --git a/codes/shell/输入和输出/处理带值的选项.sh b/codes/shell/输入和输出/处理带值的选项.sh new file mode 100644 index 0000000..3fbd65d --- /dev/null +++ b/codes/shell/输入和输出/处理带值的选项.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +# extracting command line options and values + +while [ -n "$1" ] +do + case "$1" in + -a) echo "Found the -a option" ;; + -b) param="$2" + echo "Found the -b option, with parameter value $param" + shift ;; + -c) echo "Found the -c option" ;; + --) shift + break ;; + *) echo "$1 is not an option" ;; + esac + shift +done + +count=1 +for param in "$@" +do + echo "Parameter #$count : $param" + count=$[ $count + 1 ] +done diff --git a/codes/shell/输入和输出/处理简单选项.sh b/codes/shell/输入和输出/处理简单选项.sh new file mode 100644 index 0000000..f5e5de3 --- /dev/null +++ b/codes/shell/输入和输出/处理简单选项.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +# extracting command line options as parameters + +while [ -n "$1" ] +do + case "$1" in + -a) echo "Found the -a option" ;; + -b) echo "Found the -b optins" ;; + -c) echo "Found the -c optins" ;; + *) echo "$1 is not a valid options" ;; + esac + shift +done diff --git a/codes/shell/示例脚本/输入和输出/快速清除文件或日志.sh b/codes/shell/输入和输出/快速清除文件或日志.sh similarity index 68% rename from codes/shell/示例脚本/输入和输出/快速清除文件或日志.sh rename to codes/shell/输入和输出/快速清除文件或日志.sh index bd9fa64..b7b1f74 100644 --- a/codes/shell/示例脚本/输入和输出/快速清除文件或日志.sh +++ b/codes/shell/输入和输出/快速清除文件或日志.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # 清除日志 diff --git a/codes/shell/输入和输出/抓取所有数据.sh b/codes/shell/输入和输出/抓取所有数据.sh new file mode 100644 index 0000000..fb7fa73 --- /dev/null +++ b/codes/shell/输入和输出/抓取所有数据.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +# testing $* and $@ + +count=1 +for param in "$*" +do + echo "\$* Parameter #$count = $param" + count=$[ $count + 1 ] +done + +count=1 +for param in "$@" +do + echo "\$@ Paramenter #$count = $param" + count=$[ $count + 1 ] +done diff --git a/codes/shell/示例脚本/输入和输出/永久重定向.sh b/codes/shell/输入和输出/永久重定向.sh similarity index 94% rename from codes/shell/示例脚本/输入和输出/永久重定向.sh rename to codes/shell/输入和输出/永久重定向.sh index ee7a5a0..82e51e3 100644 --- a/codes/shell/示例脚本/输入和输出/永久重定向.sh +++ b/codes/shell/输入和输出/永久重定向.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing STDERR messages # redirecting all to a file diff --git a/codes/shell/示例脚本/输入和输出/测试.txt b/codes/shell/输入和输出/测试.txt similarity index 100% rename from codes/shell/示例脚本/输入和输出/测试.txt rename to codes/shell/输入和输出/测试.txt diff --git a/codes/shell/示例脚本/输入和输出/目录操作.sh b/codes/shell/输入和输出/目录操作.sh similarity index 100% rename from codes/shell/示例脚本/输入和输出/目录操作.sh rename to codes/shell/输入和输出/目录操作.sh diff --git a/codes/shell/示例脚本/输入和输出/获取用户输入.sh b/codes/shell/输入和输出/获取用户输入.sh similarity index 92% rename from codes/shell/示例脚本/输入和输出/获取用户输入.sh rename to codes/shell/输入和输出/获取用户输入.sh index c8e33c2..24fbde3 100644 --- a/codes/shell/示例脚本/输入和输出/获取用户输入.sh +++ b/codes/shell/输入和输出/获取用户输入.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing the reading command @@ -19,7 +19,7 @@ read -p "Enter a number:" factorial=1 for (( count = 1; count <= $REPLY; count ++ )) do - factorial=$[ $factorial * $count ] + factorial=$[ $factorial * $count ] done echo "The factorial of $REPLY is $factorial" diff --git a/codes/shell/示例脚本/输入和输出/记录信息.sh b/codes/shell/输入和输出/记录信息.sh similarity index 93% rename from codes/shell/示例脚本/输入和输出/记录信息.sh rename to codes/shell/输入和输出/记录信息.sh index 84d31db..907d7e4 100644 --- a/codes/shell/示例脚本/输入和输出/记录信息.sh +++ b/codes/shell/输入和输出/记录信息.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # using the tee command for logging #将输入一边发送到STDOUT,一边发送到日志文件 diff --git a/codes/shell/示例脚本/输入和输出/读取参数.sh b/codes/shell/输入和输出/读取参数.sh similarity index 70% rename from codes/shell/示例脚本/输入和输出/读取参数.sh rename to codes/shell/输入和输出/读取参数.sh index c5f89f5..be23518 100644 --- a/codes/shell/示例脚本/输入和输出/读取参数.sh +++ b/codes/shell/输入和输出/读取参数.sh @@ -1,10 +1,10 @@ -#!/bin/bash +#!/usr/bin/env bash # using one command line parameter factorial=1 for (( number = 1; number <= $1; number ++ )) do - factorial=$[ $factorial * $number ] + factorial=$[ $factorial * $number ] done echo The factor of $1 is $factorial diff --git a/codes/shell/示例脚本/输入和输出/读取多个命令行参数.sh b/codes/shell/输入和输出/读取多个命令行参数.sh similarity index 88% rename from codes/shell/示例脚本/输入和输出/读取多个命令行参数.sh rename to codes/shell/输入和输出/读取多个命令行参数.sh index 6d2efcf..2f2f6d0 100644 --- a/codes/shell/示例脚本/输入和输出/读取多个命令行参数.sh +++ b/codes/shell/输入和输出/读取多个命令行参数.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # handing lots of parameters diff --git a/codes/shell/示例脚本/输入和输出/读取程序名.sh b/codes/shell/输入和输出/读取程序名.sh similarity index 92% rename from codes/shell/示例脚本/输入和输出/读取程序名.sh rename to codes/shell/输入和输出/读取程序名.sh index 0637a45..36941cf 100644 --- a/codes/shell/示例脚本/输入和输出/读取程序名.sh +++ b/codes/shell/输入和输出/读取程序名.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # testing the $0 parameter diff --git a/codes/shell/示例脚本/输入和输出/读取选择参数.sh b/codes/shell/输入和输出/读取选择参数.sh similarity index 82% rename from codes/shell/示例脚本/输入和输出/读取选择参数.sh rename to codes/shell/输入和输出/读取选择参数.sh index 037aa91..2e2e38f 100644 --- a/codes/shell/示例脚本/输入和输出/读取选择参数.sh +++ b/codes/shell/输入和输出/读取选择参数.sh @@ -11,8 +11,8 @@ serial=( start stop restart ) echo -n "请选择操作(可选值:start|stop|restart):" read oper if ! echo ${serial[@]} | grep -q ${oper}; then - echo "请选择正确操作(可选值:start|stop|restart)" - exit 1 + echo "请选择正确操作(可选值:start|stop|restart)" + exit 1 fi declare -a serial2 @@ -20,6 +20,6 @@ serial2=( dev test prod ) echo -n "请选择运行环境(可选值:dev|test|prod):" read profile if ! echo ${serial2[@]} | grep -q ${profile}; then - echo "请选择正确运行环境(可选值:dev|test|prod)" - exit 1 + echo "请选择正确运行环境(可选值:dev|test|prod)" + exit 1 fi diff --git a/codes/shell/输入和输出/超时和输入计数.sh b/codes/shell/输入和输出/超时和输入计数.sh new file mode 100644 index 0000000..024c4a6 --- /dev/null +++ b/codes/shell/输入和输出/超时和输入计数.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +# timing the data entry + +if read -t 5 -p "Please enter your name:" name +then + echo "Hello, $name, welcome to my script" +else + #起到换行的作用 + echo + #输入计数 -n1 + read -n1 -p "Do you want to continue [Y/N]?" answer + case $answer in + Y | y) echo + echo "Fine, continue on..." ;; + N | n) echo + echo "OK,goodbye" ;; + *) echo + echo "OK, wrong, goodbye" + esac + echo "Sorry, this is the end of the script" +fi + diff --git a/codes/shell/示例脚本/输入和输出/隐藏方式读取数据.sh b/codes/shell/输入和输出/隐藏方式读取数据.sh similarity index 90% rename from codes/shell/示例脚本/输入和输出/隐藏方式读取数据.sh rename to codes/shell/输入和输出/隐藏方式读取数据.sh index ba9b2c5..2786981 100644 --- a/codes/shell/示例脚本/输入和输出/隐藏方式读取数据.sh +++ b/codes/shell/输入和输出/隐藏方式读取数据.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # hiding input data from monitor diff --git a/codes/shell/示例脚本/进阶脚本/创建捕捉脚本.sh b/codes/shell/进阶脚本/创建捕捉脚本.sh similarity index 97% rename from codes/shell/示例脚本/进阶脚本/创建捕捉脚本.sh rename to codes/shell/进阶脚本/创建捕捉脚本.sh index dcd43a1..4c86de9 100644 --- a/codes/shell/示例脚本/进阶脚本/创建捕捉脚本.sh +++ b/codes/shell/进阶脚本/创建捕捉脚本.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Capture_Stats - Gather System Performance Statistics diff --git a/codes/shell/demos/debug-demo.sh b/codes/shell/进阶脚本/开启debug模式.sh similarity index 91% rename from codes/shell/demos/debug-demo.sh rename to codes/shell/进阶脚本/开启debug模式.sh index f1e80a9..0f75ff1 100644 --- a/codes/shell/demos/debug-demo.sh +++ b/codes/shell/进阶脚本/开启debug模式.sh @@ -3,7 +3,7 @@ # 开启 debug set -x for (( i = 0; i < 3; i ++ )); do - printf ${i} + printf ${i} done # 关闭 debug set +x @@ -22,7 +22,7 @@ set +x # + set +x for i in {1..5}; do - printf ${i}; + printf ${i}; done printf "\n" # Output: 12345 diff --git a/codes/shell/示例脚本/进阶脚本/查看uptime获取在线用户数.sh b/codes/shell/进阶脚本/查看uptime获取在线用户数.sh similarity index 71% rename from codes/shell/示例脚本/进阶脚本/查看uptime获取在线用户数.sh rename to codes/shell/进阶脚本/查看uptime获取在线用户数.sh index ebc0eab..2ac01f7 100644 --- a/codes/shell/示例脚本/进阶脚本/查看uptime获取在线用户数.sh +++ b/codes/shell/进阶脚本/查看uptime获取在线用户数.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # uptime | sed 's/user.*$//' | gawk '{print $NF}' diff --git a/codes/shell/示例脚本/进阶脚本/生成报告脚本-基于创建捕捉脚本.sh b/codes/shell/进阶脚本/生成报告脚本-基于创建捕捉脚本.sh similarity index 98% rename from codes/shell/示例脚本/进阶脚本/生成报告脚本-基于创建捕捉脚本.sh rename to codes/shell/进阶脚本/生成报告脚本-基于创建捕捉脚本.sh index 7b3d646..da98949 100644 --- a/codes/shell/示例脚本/进阶脚本/生成报告脚本-基于创建捕捉脚本.sh +++ b/codes/shell/进阶脚本/生成报告脚本-基于创建捕捉脚本.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Report_Stats - Generates Rpt from Captured Perf Stats diff --git a/codes/shell/示例脚本/进阶脚本/系统快照报告.sh b/codes/shell/进阶脚本/系统快照报告.sh similarity index 88% rename from codes/shell/示例脚本/进阶脚本/系统快照报告.sh rename to codes/shell/进阶脚本/系统快照报告.sh index 5fa363d..f3ad3c2 100644 --- a/codes/shell/示例脚本/进阶脚本/系统快照报告.sh +++ b/codes/shell/进阶脚本/系统快照报告.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Snapshot_Stats - produces a report for system stats @@ -47,8 +47,8 @@ uptime | sed -n '/,/s/,/ /gp' | gawk '{if($4 == "days" || $4 == "day") {print $2 echo for DISK in $DISK_TO_MONITOR # loop to check disk space do - echo -e "$DISK usage: \c" - df -h $DISK | sed -n '/% \//p' | gawk '{ print $5 }' + echo -e "$DISK usage: \c" + df -h $DISK | sed -n '/% \//p' | gawk '{ print $5 }' done # ################################################################## @@ -69,10 +69,10 @@ ZOMBIE_CHECK=`ps -al | gawk '{print $2,$4}' | grep Z` # if [ "$ZOMBIE_CHECK" = "" ] then - echo "No Zombie Process on System at this Time" + echo "No Zombie Process on System at this Time" else - echo "Current System Zombie Processes" - ps -al | gawk '{print $2,$4}' | grep Z + echo "Current System Zombie Processes" + ps -al | gawk '{print $2,$4}' | grep Z fi echo # diff --git a/codes/shell/示例脚本/进阶脚本/输出颜色.sh b/codes/shell/进阶脚本/输出颜色.sh similarity index 100% rename from codes/shell/示例脚本/进阶脚本/输出颜色.sh rename to codes/shell/进阶脚本/输出颜色.sh diff --git a/codes/shell/示例脚本/进阶脚本/问题跟踪数据库/Update_Problem.sh b/codes/shell/进阶脚本/问题跟踪数据库/Update_Problem.sh similarity index 58% rename from codes/shell/示例脚本/进阶脚本/问题跟踪数据库/Update_Problem.sh rename to codes/shell/进阶脚本/问题跟踪数据库/Update_Problem.sh index 99196b3..602547a 100644 --- a/codes/shell/示例脚本/进阶脚本/问题跟踪数据库/Update_Problem.sh +++ b/codes/shell/进阶脚本/问题跟踪数据库/Update_Problem.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Update_Problem - updates problem record in database @@ -15,27 +15,27 @@ MYSQL=`which mysql`" Problem_Trek -u root" # if [ $# -eq 0 ] # Check if id number was passed then -# If not passed ask for it - # - # Check if any unfinished records exist. - RECORDS_EXIST=`$MYSQL -Bse 'SELECT id_number FROM problem_logger where fixed_date="0000-00-00" OR prob_solutions=""'` - # - if [ "$RECORDS_EXIST" != "" ] - then - echo - echo "The following record(s) need updating..." - $MYSQL << EOF + # If not passed ask for it + # + # Check if any unfinished records exist. + RECORDS_EXIST=`$MYSQL -Bse 'SELECT id_number FROM problem_logger where fixed_date="0000-00-00" OR prob_solutions=""'` + # + if [ "$RECORDS_EXIST" != "" ] + then + echo + echo "The following record(s) need updating..." + $MYSQL << EOF SELECT id_number, report_date, prob_symptoms FROM problem_logger WHERE fixed_date="0000-00-00" OR prob_solutions=""\G EOF - fi - # - echo - echo "What is the ID number for the" - echo -e "problem you want to update?: \c" - read ANSWER - ID_NUMBER=$ANSWER + fi + # + echo + echo "What is the ID number for the" + echo -e "problem you want to update?: \c" + read ANSWER + ID_NUMBER=$ANSWER else - ID_NUMBER=$1 + ID_NUMBER=$1 fi # ########################################################## @@ -47,18 +47,18 @@ echo -e "Was Problem solved today? (y/n) \c" read ANSWER # case $ANSWER in - y | Y | YES | yes | Yes | yEs | yeS | YEs | yES) - # - FIXED_DATE=`date +%Y%m%d` - ;; - *) - # if answer is anything but "yes", ask for date - echo - echo -e "What was the date of resolution? [YYYYMMDD] \c" - read ANSWER - # - FIXED_DATE=$ANSWER - ;; + y | Y | YES | yes | Yes | yEs | yeS | YEs | yES) + # + FIXED_DATE=`date +%Y%m%d` + ;; + *) + # if answer is anything but "yes", ask for date + echo + echo -e "What was the date of resolution? [YYYYMMDD] \c" + read ANSWER + # + FIXED_DATE=$ANSWER + ;; esac # ######################################################## diff --git a/codes/shell/示例脚本/进阶脚本/问题跟踪数据库/查找问题.sh b/codes/shell/进阶脚本/问题跟踪数据库/查找问题.sh similarity index 68% rename from codes/shell/示例脚本/进阶脚本/问题跟踪数据库/查找问题.sh rename to codes/shell/进阶脚本/问题跟踪数据库/查找问题.sh index 253805d..04ca1e3 100644 --- a/codes/shell/示例脚本/进阶脚本/问题跟踪数据库/查找问题.sh +++ b/codes/shell/进阶脚本/问题跟踪数据库/查找问题.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Find_Problem - finds problem records using keywords @@ -15,17 +15,17 @@ MYSQL=`which mysql`" Problem_Trek -u root" # if [ -n "$1" ] # Check if a keyword was passed then -# Grab all the passed keywords - # - KEYWORDS=$@ # Grab all the params as separate words, same string + # Grab all the passed keywords + # + KEYWORDS=$@ # Grab all the params as separate words, same string # else -# Keyword(s) not passed, Ask for them - echo - echo "What keywords would you like to search for?" - echo -e "Please separate words by a space: \c" - read ANSWER - KEYWORDS=$ANSWER + # Keyword(s) not passed, Ask for them + echo + echo "What keywords would you like to search for?" + echo -e "Please separate words by a space: \c" + read ANSWER + KEYWORDS=$ANSWER fi # ####################################################### diff --git a/codes/shell/示例脚本/进阶脚本/问题跟踪数据库/记录问题.sh b/codes/shell/进阶脚本/问题跟踪数据库/记录问题.sh similarity index 88% rename from codes/shell/示例脚本/进阶脚本/问题跟踪数据库/记录问题.sh rename to codes/shell/进阶脚本/问题跟踪数据库/记录问题.sh index 4e976be..9c1b0b0 100644 --- a/codes/shell/示例脚本/进阶脚本/问题跟踪数据库/记录问题.sh +++ b/codes/shell/进阶脚本/问题跟踪数据库/记录问题.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # # Record_Problem - records system problems in database @@ -54,13 +54,13 @@ echo -e "Do you have a solution yet?(y/n) \c" read ANSWER # case $ANSWER in - y | Y | YES | yes | Yes | yEs | yeS | YEs | yES) - ./Update_Problem.sh $id - # - ;; - *) - # if answer is anything but yes, just exit script - ;; + y | Y | YES | yes | Yes | yEs | yeS | YEs | yES) + ./Update_Problem.sh $id + # + ;; + *) + # if answer is anything but yes, just exit script + ;; esac # ############################################################ diff --git a/codes/shell/示例脚本/逻辑控制/bash-shell无法处理浮点数.sh b/codes/shell/逻辑控制/bash-shell无法处理浮点数.sh similarity index 79% rename from codes/shell/示例脚本/逻辑控制/bash-shell无法处理浮点数.sh rename to codes/shell/逻辑控制/bash-shell无法处理浮点数.sh index 85a1c54..35eefb5 100644 --- a/codes/shell/示例脚本/逻辑控制/bash-shell无法处理浮点数.sh +++ b/codes/shell/逻辑控制/bash-shell无法处理浮点数.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #bash shell 仅能处理浮点数值,test命令无法处理val1变量中存储的浮点值 @@ -8,5 +8,5 @@ val1=`echo "scale=4; 10 / 3" | bc` echo "The test value is $val1" if [ $val1 -gt 3 ] then - echo "The result is larger than 3" + echo "The result is larger than 3" fi diff --git a/codes/shell/示例脚本/逻辑控制/break使用示例.sh b/codes/shell/逻辑控制/break示例.sh similarity index 100% rename from codes/shell/示例脚本/逻辑控制/break使用示例.sh rename to codes/shell/逻辑控制/break示例.sh diff --git a/codes/shell/逻辑控制/case示例.sh b/codes/shell/逻辑控制/case示例.sh new file mode 100644 index 0000000..ad9dbb1 --- /dev/null +++ b/codes/shell/逻辑控制/case示例.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +echo "input param: " $1 $2 $3 + +x=0 +if [[ -n $1 ]]; then + x=$1 +fi + +oper="" +if [[ -n $2 ]]; then + oper=$2 +fi + +y=0 +if [[ -n $3 ]]; then + y=$3 +fi + +exec +case ${oper} in + + | add) + val=`expr ${x} + ${y}` + echo "${x} + ${y} = ${val}" + ;; + - | sub) + val=`expr ${x} - ${y}` + echo "${x} - ${y} = ${val}" + ;; + * | mul) + val=`expr ${x} \* ${y}` + echo "${x} * ${y} = ${val}" + ;; + / | div) + val=`expr ${x} / ${y}` + echo "${x} / ${y} = ${val}" + ;; + *) + echo "Unknown oper!" + ;; +esac diff --git a/codes/shell/示例脚本/逻辑控制/continue使用示例.sh b/codes/shell/逻辑控制/continue示例.sh similarity index 100% rename from codes/shell/示例脚本/逻辑控制/continue使用示例.sh rename to codes/shell/逻辑控制/continue示例.sh diff --git a/codes/shell/示例脚本/逻辑控制/for循环使用示例.sh b/codes/shell/逻辑控制/for循环示例.sh similarity index 100% rename from codes/shell/示例脚本/逻辑控制/for循环使用示例.sh rename to codes/shell/逻辑控制/for循环示例.sh diff --git a/codes/shell/示例脚本/逻辑控制/if-elif-else使用示例.sh b/codes/shell/逻辑控制/if-elif-else示例.sh similarity index 72% rename from codes/shell/示例脚本/逻辑控制/if-elif-else使用示例.sh rename to codes/shell/逻辑控制/if-elif-else示例.sh index 408e32a..e9ed676 100644 --- a/codes/shell/示例脚本/逻辑控制/if-elif-else使用示例.sh +++ b/codes/shell/逻辑控制/if-elif-else示例.sh @@ -3,22 +3,22 @@ ################### if 语句 ################### # 写成一行 if [[ 1 -eq 1 ]]; then - echo "1 -eq 1 result is: true"; + echo "1 -eq 1 result is: true"; fi # Output: 1 -eq 1 result is: true # 写成多行 if [[ "abc" -eq "abc" ]] then - echo ""abc" -eq "abc" result is: true" + echo ""abc" -eq "abc" result is: true" fi # Output: abc -eq abc result is: true ################### if else 语句 ################### if [[ 2 -ne 1 ]]; then - echo "true" + echo "true" else - echo "false" + echo "false" fi # Output: true @@ -26,10 +26,10 @@ fi x=10 y=20 if [[ ${x} > ${y} ]]; then - echo "${x} > ${y}" + echo "${x} > ${y}" elif [[ ${x} < ${y} ]]; then - echo "${x} < ${y}" + echo "${x} < ${y}" else - echo "${x} = ${y}" + echo "${x} = ${y}" fi # Output: 10 < 20 diff --git a/codes/shell/示例脚本/逻辑控制/output.txt b/codes/shell/逻辑控制/output.txt similarity index 100% rename from codes/shell/示例脚本/逻辑控制/output.txt rename to codes/shell/逻辑控制/output.txt diff --git a/codes/shell/demos/statement/select-demo.sh b/codes/shell/逻辑控制/select菜单示例.sh similarity index 57% rename from codes/shell/demos/statement/select-demo.sh rename to codes/shell/逻辑控制/select菜单示例.sh index 4e59b5a..ef786da 100644 --- a/codes/shell/demos/statement/select-demo.sh +++ b/codes/shell/逻辑控制/select菜单示例.sh @@ -5,10 +5,10 @@ select ITEM in bower npm gem pip do echo -n "Enter the package name: " && read PACKAGE case ${ITEM} in - bower) bower install ${PACKAGE} ;; - npm) npm install ${PACKAGE} ;; - gem) gem install ${PACKAGE} ;; - pip) pip install ${PACKAGE} ;; + bower) bower install ${PACKAGE} ;; + npm) npm install ${PACKAGE} ;; + gem) gem install ${PACKAGE} ;; + pip) pip install ${PACKAGE} ;; esac break # 避免无限循环 done diff --git a/codes/shell/示例脚本/逻辑控制/until使用示例.sh b/codes/shell/逻辑控制/until示例.sh similarity index 100% rename from codes/shell/示例脚本/逻辑控制/until使用示例.sh rename to codes/shell/逻辑控制/until示例.sh diff --git a/codes/shell/示例脚本/逻辑控制/while循环使用示例.sh b/codes/shell/逻辑控制/while循环示例.sh similarity index 100% rename from codes/shell/示例脚本/逻辑控制/while循环使用示例.sh rename to codes/shell/逻辑控制/while循环示例.sh diff --git a/codes/shell/示例脚本/逻辑控制/从命令读取值.sh b/codes/shell/逻辑控制/从命令读取值.sh similarity index 84% rename from codes/shell/示例脚本/逻辑控制/从命令读取值.sh rename to codes/shell/逻辑控制/从命令读取值.sh index 8e97888..3f8c496 100644 --- a/codes/shell/示例脚本/逻辑控制/从命令读取值.sh +++ b/codes/shell/逻辑控制/从命令读取值.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #reading values from a file @@ -15,5 +15,5 @@ IFS=$'\n' for state in `cat $file` do - echo "Visit beautiful $state" + echo "Visit beautiful $state" done diff --git a/codes/shell/逻辑控制/使用双圆括号.sh b/codes/shell/逻辑控制/使用双圆括号.sh new file mode 100644 index 0000000..2600212 --- /dev/null +++ b/codes/shell/逻辑控制/使用双圆括号.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +# using double parenthesis + +var1=10 + +if (($var1 ** 2 > 90)) +then + ((var2 = $var1 ** 2)) + echo "The square of $var1 if $var2" +fi + diff --git a/codes/shell/逻辑控制/使用双方括号.sh b/codes/shell/逻辑控制/使用双方括号.sh new file mode 100644 index 0000000..8b9ce3f --- /dev/null +++ b/codes/shell/逻辑控制/使用双方括号.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# using pattern matching + +if [[ $USER == r* ]] +then + echo "Hello $USER" +else + echo "Sorry, I do not know you" +fi diff --git a/codes/shell/示例脚本/逻辑控制/使用大于小于号.sh b/codes/shell/逻辑控制/使用大于小于号.sh similarity index 85% rename from codes/shell/示例脚本/逻辑控制/使用大于小于号.sh rename to codes/shell/逻辑控制/使用大于小于号.sh index 728832c..dcb5880 100644 --- a/codes/shell/示例脚本/逻辑控制/使用大于小于号.sh +++ b/codes/shell/逻辑控制/使用大于小于号.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # 大于小于号必须转义,否则shell会将它们当做重定向符号而把字符串值当做文件名处理 # 大于小于号顺序和sort命令所采用的有所不同 @@ -10,9 +10,9 @@ val2=hockey ################### 错误使用大于小于号 ################## if [[ $val1 > $val2 ]] then - echo "$val1 is greater than $val2" + echo "$val1 is greater than $val2" else - echo "$val1 is less than $val2" + echo "$val1 is less than $val2" fi ################### 正确使用大于小于号 ################### diff --git a/codes/shell/逻辑控制/使用嵌套循环并修改IFS.sh b/codes/shell/逻辑控制/使用嵌套循环并修改IFS.sh new file mode 100644 index 0000000..b1c406c --- /dev/null +++ b/codes/shell/逻辑控制/使用嵌套循环并修改IFS.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +#changing the IFS value + +IFS.OLD=$IFS +IFS=$'\n' +for entry in `cat /etc/passwd` +do + echo "Values in $entry -" + IFS=: + for value in $entry + do + echo " $value" + done +done diff --git a/codes/shell/示例脚本/逻辑控制/使用管道或重定向.sh b/codes/shell/逻辑控制/使用管道或重定向.sh similarity index 56% rename from codes/shell/示例脚本/逻辑控制/使用管道或重定向.sh rename to codes/shell/逻辑控制/使用管道或重定向.sh index 9e20100..354c6c5 100644 --- a/codes/shell/示例脚本/逻辑控制/使用管道或重定向.sh +++ b/codes/shell/逻辑控制/使用管道或重定向.sh @@ -1,20 +1,20 @@ -#!/bin/bash +#!/usr/bin/env bash # redirecting the for output to a file for file in /home/tiandi/* do - if [ -d "$file" ] - then - echo "$file is a directory" - else - echo "$file is a file" - fi + if [ -d "$file" ] + then + echo "$file is a directory" + else + echo "$file is a file" + fi done > output.txt # piping a loop to another command for state in "North Dakota" Connecticut do - echo "$state is next place to go" + echo "$state is next place to go" done | sort echo "This completes our travels" diff --git a/codes/shell/逻辑控制/使用通配符处理目录.sh b/codes/shell/逻辑控制/使用通配符处理目录.sh new file mode 100644 index 0000000..81d03d7 --- /dev/null +++ b/codes/shell/逻辑控制/使用通配符处理目录.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +#iterate through all the files in a directory +for file in /home/tiandi/test/* +do + if [ -d "$file" ] + then + echo "$file is a directory" + elif [ -f "$file" ] + then + echo "$file is a file" + fi +done diff --git a/codes/shell/示例脚本/逻辑控制/注意test大小写顺序和sort不同.sh b/codes/shell/逻辑控制/注意test大小写顺序和sort不同.sh similarity index 79% rename from codes/shell/示例脚本/逻辑控制/注意test大小写顺序和sort不同.sh rename to codes/shell/逻辑控制/注意test大小写顺序和sort不同.sh index 2ea2de5..282001b 100644 --- a/codes/shell/示例脚本/逻辑控制/注意test大小写顺序和sort不同.sh +++ b/codes/shell/逻辑控制/注意test大小写顺序和sort不同.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash #test命令中,大小字母会被当成小于小写字符,而在sort中,小写字母会先出现,test使用标准的ASCII排序,sort使用本地化语言设置进行排序,对于英语,本地化设置制定了排序顺序中小写字母出现在大写字母之前 @@ -7,7 +7,7 @@ var2=testing if [ $val1 \> $val2 ] then - echo '$val1 is greater than $val2' + echo '$val1 is greater than $val2' else - echo '$val1 is less than $val2' + echo '$val1 is less than $val2' fi diff --git a/codes/shell/示例脚本/逻辑控制/读取里表中复杂的值.sh b/codes/shell/逻辑控制/读取里表中复杂的值.sh similarity index 72% rename from codes/shell/示例脚本/逻辑控制/读取里表中复杂的值.sh rename to codes/shell/逻辑控制/读取里表中复杂的值.sh index d8723d7..bae02da 100644 --- a/codes/shell/示例脚本/逻辑控制/读取里表中复杂的值.sh +++ b/codes/shell/逻辑控制/读取里表中复杂的值.sh @@ -1,8 +1,8 @@ -#!/bin/bash +#!/usr/bin/env bash # another example of how not to use the for command for test in I don't know if this'll work do - echo "word:$test" + echo "word:$test" done diff --git a/docs/README.md b/docs/README.md index 04ce5d0..086c933 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,13 +4,15 @@ > > 📖 [电子书](https://dunwu.github.io/linux-tutorial/) | [电子书(国内)](http://turnon.gitee.io/linux-tutorial/) -| :wrench: | :shell: | :memo: | 📚 | -| :-------------------: | :-------------------: | :---------------: | :-------------------: | -| [软件运维](#软件运维) | [运维和脚本](#运维和脚本) | [知识点](#知识点) | [学习资源](#学习资源) | +| 🛠 | 🐚 | 📝 | 📚 | +| :-------------------: | :-----------------------: | :-----------: | :-------------------: | +| [软件运维](#软件运维) | [Shell 脚本](#Shell-脚本) | [教程](#教程) | [学习资源](#学习资源) | ## 软件运维 > 本章节内容介绍日常开发中常见的一些软件、工具的安装、配置。 +> +> 配套安装脚本:🐚 [软件运维配置脚本集合](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/soft) - 开发环境 - [JDK 安装](linux/soft/jdk-install.md) @@ -35,22 +37,21 @@ - [Mongodb 运维](linux/soft/mongodb-ops.md) - [Redis 运维](linux/soft/redis-ops.md) -## 运维和脚本 +## Shell 脚本 -- [系统运维脚本集合](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/sys) -- [软件运维配置脚本集合](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/soft) -- [工具脚本集合](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/soft) -- [Vim 应用指南](linux/ops/vim.md) -- [Zsh 应用指南](linux/ops/zsh.md) -- [Shell 教程](linux/ops/shell.md) -- [Python 教程](linux/ops/python.md) -- [Systemd 入门教程](linux/ops/systemd.md) +### Shell 脚本大全 -> 提供一键式运维、配置软件脚本 +**Shell 脚本大全** 精心收集、整理了 Linux 环境下的常见 Shell 脚本操作片段。 -## 知识点 +源码:[**Shell 脚本大全**](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/sys) -### Linux +### CentOS 常规操作运维脚本集合 + +本人作为一名 Java 后端,苦于经常在 CentOS 环境上开荒虚拟机。为提高效率,写了一套 Shell 脚本,提供如下功能:安装常用 lib 库、命令工具、设置 DNS、NTP、配置国内 yum 源、一键安装常用软件等。 + +源码:[**CentOS 常规操作运维脚本集合**](https://github.com/dunwu/linux-tutorial/tree/master/codes/linux/sys) + +## 教程 - [Linux 命令教程](linux/cli/README.md) - [查看 Linux 命令帮助信息](linux/cli/查看Linux命令帮助信息.md) @@ -62,23 +63,23 @@ - [Linux 网络管理](linux/cli/Linux网络管理.md) - [Linux 硬件管理](linux/cli/Linux硬件管理.md) - [Linux 软件管理](linux/cli/Linux硬件管理.md) -- [Linux 运维](linux/ops/README.md) - - [linux 典型运维应用](linux/ops/linux典型运维应用.md) - - [samba 使用详解](linux/ops/samba使用详解.md) - -### Docker - - [Docker 教程](docker) - [Docker 应用指南](docker/docker.md) - [Docker Cheat Sheet](docker/docker-cheat-sheet.md) - -### Git - - [Git 教程](git/README.md) - [Git 快速指南](git/git-quickstart.md) - [Git 配置](git/git-configuration.md) - [git-flow 工作流](git/git-flow.md) - [Git 常见问题](git/git-faq.md) +- 运维 + - [linux 典型运维应用](linux/ops/linux典型运维应用.md) + - [samba 使用详解](linux/ops/samba使用详解.md) + - [Systemd 教程](linux/ops/systemd.md) +- 脚本 + - [Vim 应用指南](linux/ops/vim.md) + - [Zsh 应用指南](linux/ops/zsh.md) + - [Shell 教程](linux/ops/shell.md) + - [Python 教程](linux/ops/python.md) ## 学习资源 diff --git a/docs/index.html b/docs/index.html index 4169736..3c2dab5 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,220 +1,235 @@ - - Linux Tutorial - - - - - - - + + - + - + + @media (max-width: 600px) { + .markdown-section pre > code { + padding-top: 5px; + padding-bottom: 5px; + } + + pre:after { + content: "" !important; + } + } + + @media (min-width: 600px) { + pre code { + padding-left: 20px !important; + } + } + + @media (max-width: 600px) { + pre { + padding-left: 0px !important; + padding-right: 0px !important; + } + } +
正在加载...