git,bash - 例子整理

文章目录

    • git,bash - 例子整理
    • 概述
    • 笔记
    • 遍历目录,找到目标文件后干活
    • 备份一个文件
    • html_url_clear.sh
    • END

git,bash - 例子整理

概述

在git bash中的脚本和linux bash中好像差不多。
整理一些例子,为以后做参考

笔记

遍历目录,找到目标文件后干活

#!/bin/bash
# git bash 脚本 - 遍历修改当前目录下得所有 .gitmodules , 替换https 库 url 到 ssh 库 url

# 前置操作 : 写好my_task.sh后,给执行权限
# chmod 777 ./my_task.sh

# 前置操作 : 检查脚本的语法是否正确?
# bash -n my_task.sh
# 如果没看到输出,就说明脚本语法是正确的

# 运行脚本
# 进入到脚本的目录
# ./my_task.sh

clear
echo "---------- my_task.sh running ----------"

# echo "current user:(" $(whoami) ")"

# log begin time
echo "begin : ($(date '+%Y-%m-%d %H:%M:%S'))"

# =号两边不能有空格
file_cnt=0

find . -type f -name ".gitmodules" -print0 | while IFS= read -r -d '' file; do
    dir=$(dirname "$file")
    (
        cd "$dir" || { echo "⚠️ dir switch err: $dir"; exit 1; }
        
        # echo "finding $(pwd)/.gitmodules"
        if [ -f "$(pwd)/.gitmodules" ]; then 
            echo "!!! ($((file_cnt + 1))) was found $(pwd)/.gitmodules, ready to process"
            sed -i 's|https://github.com/|[email protected]:|g' .gitmodules
            git submodule sync --recursive
        fi    
    )

    file_cnt=$((file_cnt + 1))
done

# log end time
echo "end   : ($(date '+%Y-%m-%d %H:%M:%S'))"

备份一个文件

#!/bin/bash

# file - bk_file.sh

# function - 从命令行给定一个文件名 e.g. a.html, 备份为 a.html.bk

# run env = git bash

# sh begin
clear
echo "task begin, please wait a moment"

# 命令行参数检查

# echo "param count = $#"
# param count = 0
# 如果不给命令行参数,那么参数个数 $# 就为 0

if [ $# -ne 1 ]; then
    echo "usage : $0 "
    echo "must give a file path name to operation"
    exit 1
fi


# 文件存在性检查
if [ ! -f "$1" ]; then 
    echo "Error: File [$1] does not exist." 
    exit 1 
else 
    echo "ok - File [$1] exists." 
fi

# 执行备份操作
cp "$1" "$1.bk"

# 判断上一个命令是否执行成功
if [ $? -ne 0 ]; then
    echo "failed - cp "$1" "$1.bk""
    exit 1
fi

# 检查备份文件是否存在
if [ ! -f "$1.bk" ]; then 
    echo "error - back up file [$1.bk]" 
    exit 1 
else 
    echo "ok - back up File [$1.bk]" 
fi


# sh end
echo "END"

html_url_clear.sh

#!/bin/bash

# @file html_url_clear.sh
# @function replace the url in html to empty

clear

if [ $# -ne 1 ]; then
    echo "usage : $0 "
    echo "must give a file path name to operation"
    exit 1
fi

./bk_file.sh $1

if [ $? -ne 0 ]; then
    echo "failed - back up file <"$1">"
    exit 1
fi

echo "ok - process continue"

target_file=$1

sed -i -E \
-e 's/xmlns="[^"]*"/xmlns=""/g' \
-e 's/src="[^"]*"/src=""/g' \
-e "s/src='[^']*'/src=''/g" \
-e 's/href="[^"]*"/href=""/g' \
-e "s#href='[^']*'#href=''#g" \
-e 's/onclick="[^"]*"/onclick=""/g' \
-e "s/location='[^']*'/location=''/g" \
-e "s#window.open\('[^']*'#window.open\(''#g" \
-e 's/action="[^"]*"/action=""/g' \
"$target_file"

echo -e "\033[32 mprocess over: \033[36m $target_file \033[32m 'url was all clear to empty\033[0m"
exit 0

END

你可能感兴趣的:(git,bash,git,bash)