shell脚本管理工具

作者: RingKun | 来源:发表于2019-11-13 15:55 被阅读0次

    功能:
    1、通过简单的命令行添加修改shell脚本。
    2、增加分类功能,让自己的环境变量分类清晰。
    3、快速查看脚本。
    安装:
    1、文件名存储为eshell.py,执行命令python3 eshell.py install(需安装python3)
    2、source ~/.bash_profile
    使用示例:
    1、eshell add java 'export java=/Users/xxxx/jdk/java' 添加分类java,并新增脚本。添加完成后执行reshell生效。
    2、eshell list 显示所有分类
    3、eshell list java 显示java分类下定义的脚本
    4、eshell rm java 移除java类的所有脚本
    5、
    a、eshell vim iterm 手动编辑(需安装vim)。修改完成后执行reshell生效。
    b、输入以下内容:

    echo '配置iterm'
    export CLICOLOR=1
    export LSCOLORS=gxfxcxdxbxegedabagacad
    export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;36m\]\w\[\033[00m\]\$ '
    export TERM=xterm-256color
    

    c、reshell

    eshell.py:

    
    import os
    import sys
    import subprocess
    import datetime
    
    _PYTHON = 'default'
    _ENCODING = 'utf-8'
    _BAK_PREFIX = 'bak/'
    
    
    class Log(object):
    
        def __init__(self, debug):
            self.debug = debug
    
        def debug(self, msg):
            # if self.debug is True:
            print_on_screen(msg)
    
        @classmethod
        def info(self, msg):
            print(msg)
    
    
    log: Log = None
    
    
    def shell_str(s):
        return '\'{}\''.format(s)
    
    
    def create_backup_name(list):
        return eshell_dir() + os.path.sep + _BAK_PREFIX + list + '-' + str(datetime.datetime.now())
    
    
    def back_up(list):
        command = 'cp \'{0}\' \'{1}\''.format(cmd_list_path(list), create_backup_name(list))
        # log.debug(command)
        print_on_screen(command)
        os.system(command)
    
    
    def print_on_screen(s):
        os.system('echo ' + '\'{}\''.format(s))
    
    
    def bash_sh_path():
        return subprocess.getoutput('echo ~/.bash_profile')
    
    
    def source_bash_shell():
        return os.system('source ' + bash_sh_path())
    
    
    def eshell_dir():
        root_path = subprocess.getoutput('echo ~')
        dir_path = root_path + '/.eshell'
        return dir_path
    
    
    def cmd_list_path(cmd_list):
        return eshell_dir() + '/' + cmd_list
    
    
    def edit_file_replace(file_path, old_str, new_str):
        with open(file_path, 'r', encoding=_ENCODING) as fr:
            content = fr.read()
        content = content.replace(old_str, new_str)
        with open(file_path, "w", encoding = _ENCODING) as fw:
            fw.write(content)
    
    
    def read_cmd_list_file(cmd_list):
        cmd_list_check(cmd_list)
        with open(cmd_list_path(cmd_list), 'r', encoding=_ENCODING) as fr:
            return fr.read()
    
    
    def write_cmd_list_file(cmd_list, cmd):
        cmd_list_check(cmd_list)
        text = read_cmd_list_file(cmd_list)
        if cmd is None or cmd == '':
            return
        if cmd in text:
            print_on_screen('****** Already exists, Not added again! *******')
            return
        if text is None or text == '':
            text = cmd
        else:
            text = text + '\n' + cmd
        with open(cmd_list_path(cmd_list), 'w', encoding='utf-8') as fw:
            fw.write(text)
    
    
    def eshell_dir_check():
        dir_path = eshell_dir()
        if os.path.exists(dir_path) is False:
            os.system('mkdir ' + dir_path)
    
        dir_path = eshell_dir()
        if os.path.exists(dir_path + '/bak') is False:
            os.system('mkdir ' + dir_path+'/bak')
        return dir_path
    
    
    def cmd_list_check(cmd_list):
        eshell_dir_check()
        file_path = cmd_list_path(cmd_list)
        if os.path.exists(file_path) is False:
            os.system('touch ' + file_path)
        return file_path
    
    
    def bash_profile_add_list(cmd_list):
        # 配置bash_profile
        with open(bash_sh_path(), 'r', encoding=_ENCODING) as fr:
            bash_profile = fr.read()
        new_sh = '\nsource ' + cmd_list_path(cmd_list)
        if new_sh not in bash_profile:
            finish_sh = bash_profile + new_sh
            with open(bash_sh_path(), 'w', encoding=_ENCODING) as fw:
                fw.write(finish_sh)
    
    
    def bash_profile_rm_list(cmd_list):
        # 配置bash_profile
        with open(bash_sh_path(), 'r', encoding=_ENCODING) as fr:
            bash_profile = fr.read()
        new_sh = '\nsource ' + cmd_list_path(cmd_list)
        finish_sh = bash_profile.replace(new_sh, '')
        with open(bash_sh_path(), 'w', encoding=_ENCODING) as fw:
            fw.write(finish_sh)
    
    
    def all_list()->(str, set):
        files = os.listdir(eshell_dir())
        list = set()
        list_text = ''
        for file in files:
            if file != 'init' and file != 'eshell.py' \
                    and '.swp' not in file and os.path.isfile(eshell_dir() + os.path.sep + file):
                list_text = list_text + file + '  '
                list.add(file)
        return list_text, list
    
    
    def add_cmd_list_command(cmd_list, command):
        if cmd_list is None:
            print_on_screen('eshell add [cmd_list] [command]')
            return
        write_cmd_list_file(cmd_list, command)
        bash_profile_add_list(cmd_list)
        source_bash_shell()
        print_on_screen('Please run: source {0}, or exec: reshell, or active this in a new tab.'.format(bash_sh_path()))
    
    
    if __name__ == '__main__':
        _PYTHON = sys.executable
        try:
            # show_all_cmd()
            arg1 = None
            arg2 = None
            arg3 = None
            arg4 = None
            try:
                arg0 = sys.argv[0]
                arg1 = sys.argv[1]
                arg2 = sys.argv[2]
                arg3 = sys.argv[3]
                arg4 = sys.argv[4]
            except BaseException as e:
                a = 1
            log = Log(arg1 == "main.py")
            if arg1 == 'install':
                py_path = os.path.abspath(__file__)
                print_on_screen('current path:' + py_path)
                dest_dir = eshell_dir_check()
                dest_path = dest_dir + '/' + 'eshell.py'
                print_on_screen('copy to: ' + dest_path)
                os.system('cp {0} {1}'.format(py_path, dest_path))
                edit_file_replace(dest_path, '_PYTHON = \'default\'', "_PYTHON = " + "'" + _PYTHON + "'")
                add_cmd_list_command('init', 'alias eshell=\'{0}\''.format(_PYTHON + ' ' + dest_path))
                add_cmd_list_command('init', 'alias reshell=' + "'" + 'source ' + bash_sh_path() + "'")
    
            if arg1 is None or arg1 == '--help':
                print_on_screen('eshell add list command        :  ## add new shell command')
                print_on_screen('eshell list                    :  ## show all list')
                print_on_screen('eshell list list               :  ## show all commands in one list')
                print_on_screen('eshell rm list1 list2 list3... :  ## delete list')
    
            if arg1 == 'list':
                list = arg2
                if list is None:
                    list_text, list = all_list()
                    print_on_screen(list_text)
                else:
                    text = read_cmd_list_file(list)
                    print_on_screen(text)
            if arg1 == 'add':
                add_cmd_list_command(arg2, arg3)
                source_bash_shell()
            if arg1 == 'vim':
                list_text, list = all_list()
                if arg2 in list:
                    # log.debug(list)
                    os.system('vim ' + cmd_list_path(arg2))
                else:
                    # log.debug(list)
                    decision = input("No This list, Add new[Y/n]:")
                    if decision.lower() == 'y':
                        os.system('vim ' + cmd_list_path(arg2))
                    else:
                        print_on_screen('canceled!!!')
                source_bash_shell()
            if arg1 == 'rm':
                decision = input("Can't recover, really delete?[Y/n]:")
                if decision.lower() == 'y':
                    for i in range(len(sys.argv)):
                        if i >= 2:
                            back_up(sys.argv[i])
                            os.system('rm ' + cmd_list_path(sys.argv[i]))
                            bash_profile_rm_list(sys.argv[i])
                    source_bash_shell()
                else:
                    print_on_screen('canceled!!!')
        except BaseException as e:
            print_on_screen(e)
    

    相关文章

      网友评论

        本文标题:shell脚本管理工具

        本文链接:https://www.haomeiwen.com/subject/efahictx.html