working on it ...

Filters

Explore Public Snippets

Sort by

Found 5 snippets

    public by gwarah modified Aug 18, 2019  762  5  6  0

    Is a file in a directory tree?

    This script is a shell function that performs exactly this check, even if the parameters are symbolic links and/or relative directories. See "How to Use" section to install this snippet
    #!/bin/bash
    # /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    # * File       : dircontains.sh
    # * Goal       : checks if <parent> direcory contains <file>
    # * Requisites :
    # *     1. SHELL=bash
    # * History    :
    # *   #version;date;description
    # *   0.2.0; 29/07/2018; now can check if any kind of file is in <parent>
    # *   0.1.0; 27/07/2018; first release (tested in bash environment)
    # */
    
    #
    # Tested in: ubuntu 16.04/bash
    #
    
    #
    # How to use
    #
    # 1. put this script into a directory (Ex: ~/scripts)
    #
    # 2. insert this code in your ~/.bashrc:
    # . ~/scripts/dircontains.sh
    #
    # 3. open a new shell session and test it:
    #
    # dircontains <dir_parent> <file>
    #
    # 4.
    # the result is in $? var
    # $?=0, <file> is in <dir_parent>
    # $?=1, <file> is not in <dir_parent>
    # $?=2, error
    #
    
    function dircontains_syntax {
        local msg=$1
        echo "${msg}" >&2
        echo "syntax: dircontains <parent> <file>" >&2
        return 1
    }
    
    function dircontains {
        local result=1
        local parent=""
        local parent_pwd=""
        local child=""
        local child_dir=""
        local child_pwd=""
        local curdir="$(pwd)"
        local v_aux=""
    
        # parameters checking
        if [ $# -ne 2 ]; then
            dircontains_syntax "exactly 2 parameters required"
            return 2
        fi
        parent="${1}"
        child="${2}"
        
        # exchange to absolute path
        parent="$(readlink -f "${parent}")"
        child="$(readlink -f "${child}")"
        dir_child="${child}"
    
        # file/directory checking
        if [ ! -d "${parent}" ];  then
            dircontains_syntax "parent dir ${parent} not a directory or doesn't exist"
            return 2
        elif [ ! -e "${child}" ];  then
            dircontains_syntax "file ${child} not found"
            return 2
        elif [ ! -d "${child}" ];  then
            # not directory? get the path of file
            dir_child=`dirname "${child}"`
        fi
    
        # get directories from $(pwd)
        cd "${parent}"
        parent_pwd="$(pwd)"
        cd "${curdir}"  # to avoid errors due relative paths
        cd "${dir_child}"
        child_pwd="$(pwd)"
    
        # checking if is parent
        [ "${child_pwd:0:${#parent_pwd}}" = "${parent_pwd}" ] && result=0
    
        # return to current directory
        cd "${curdir}"
        return $result
    }												

    public by gwarah modified Nov 27, 2018  69  0  3  0

    Gedit snippet: Smart header

    This gedit snippet helps you create a bash header using the gedit manage tools. See the instructions in the code to install it.
    #!/bin/bash
    # Company    : ${1:your_company}
    # Project    : ${2:your_project}
    # File       : ${3:this_script.sh}
    # Goal       : ${4:goal of script}
    # Requisites :
    #   1. use only as gedit snippet
    # History    :
    #   #version;author id;date;description
    #   0.0.1a;${5:my_initials};$(date +'%d/%m/%Y %H:%M:%S');creation
    # 
    
    ######## gedit header snippet #########
    
    #
    # gedit shell header snippet
    # vs. 1.0  - 27/11/2018
    #
    # instructions:
    #
    # 1. open gedit and go to tools - Manage Snippets -sh extension
    # 2. put in there the code above "gedit header snippet" line
    # 3. give a name to the trigger and snippet. Ex: In my case sh.header to both
    # 4. if this snippet would be called many times, I've suggested you use a shortcut key. Ex: <ctrl>+<alt>+h
    # 5. open a bash file and type <trigger_name>+<tab>, or press the shortcut key related it
    # 6. fill ${1}, ${2} ... parameters. <tab>/<shift>+<tab> switch to next/previous parameter
    # 												

    public by gwarah modified Nov 13, 2018  95  1  4  1

    Ubuntu desktop file to create a folder link

    This desktop file drives you to run a script that provides this. obs: install the crsln.sh script to allow creating the symbolic link (instructions below)
    #!/usr/bin/env xdg-open
    # program     : link2folder.desktop
    # description : ubuntu desktop file to create symlink folder using gnome dialogs boxes
    # author      : lp (Luís Pessoa)
    # version     : 0.1.0b
    # history     :
    #   lp; 09/02/2018; first release
    
    # dependences : 
    #   1) OS      : ubuntu or other OS that support *.desktop files
    #   2) script  : crsln.sh have to be installed previously
    #   3) more information see restrictions to create symlinks and desktop files, man ln 
    
    # how to install:
    # 1) install the script crsln.sh: 
    #       <snip2code root url>/Snippet/4002757/Create-a-symbolic-link-with-a-file-dialo
    # 2) set the properties Exec and Icon
    #       Exec=/path/to/script/crsln.sh -d
    #       Icon=/path/to/icon/folder-remote.png
    # 3) save this file in your desktop folder and execute 
    #       chmod +x link2folder.desktop
    
    [Desktop Entry]
    Encoding=UTF-8
    Name=link2foder
    Name[pt_BR]=link2foder
    Comment=create a directory symlink
    Comment[pt_BR]=cria link simbólico de um diretório
    Exec=/path/to/script/crsln.sh -d
    Icon=/path/to/icon/folder-remote.png
    Terminal=true
    Type=Application
    Categories=Utility;Application;																														

    public by gwarah modified Nov 12, 2018  159  2  4  0

    Create a symbolic link with file dialogs

    This script provides an easy way to create file (or folder) symbolic link using zenity file dialogs. requisites: It won't run in case of any restriction related creating symlink command (ln -s ...) or if zenity package wouldn't be installed. The syntax is very simple: crsln.sh [-f|-d] [/path/to/file_or_directory [/path/to/link_name]] [
    #!/bin/bash
    # program     : crsln.sh
    # description : create a symlink with zenity file dialog
    # author      : lp (Luís Pessoa)
    # version     : 0.1.0b
    # syntax      : 
    # 	  crsln.sh [-f|-d] [/path/to/file_or_directory] [/path/to/link_name]] 
    # dependences : 
    #   1) shell: bash  
    #   2) package: zenity
    #   3) see restrictions to create a symlink, man ln
    # history     :
    #   lp; 09/02/2018; first release
    #   lp; 12/12/2017; begin of development
    
    
    # syntax get_file
    function syntax {
        local SINTAX=""
        SINTAX=$1
        SINTAX+="\n syntax: get_file [-t <title>] [ -f <file_or_dir_selected> ] [-l <filters>]"
        SYNTAX+="\n for <filters> rules see: zenity --help-file-selection"
        
        echo -e "Error: ${SINTAX} \n" >&2
        return 1
    }
    
    # syntax script
    function syntax_main {
        local SINTAX=""
        SINTAX=$1
        SINTAX+="\n syntax: create_symlink.sh [-d|-f] [file_or_directory [link_name]]"
        SYNTAX+="\n for <filters> rules see: zenity --help-file-selection"
        
        echo -e "Error: ${SINTAX} \n" >&2
        return 1
    }
    
    # catch a directory or file
    function dir_or_file {
        local opc
        local pkey=""
        RETORNO=0
        
        # 0: zenity; 1: dialog; 2: shell
        local dialog_type=${DIALOG_TYPE}
    
        if [ $dialog_type -eq 0 ]; then
            opc=$(zenity --list  \
                --text "Target is file or directory?" \
                --radiolist  --column "Check" --column "Options" \
                TRUE "file" FALSE "directory" --separator=" ")
            case $? in
            1)
                    echo "Opção deve ser selecionada" >&2
                    return 1
                    ;;
            -1)
                    echo "Ocorreu um erro na seleção de opções"
                    return 1
                    ;;
            esac
        else
            syntax "dialog type not implemented yet."
            return 1
        fi
        
        echo "${opc}"
        return $RETORNO
    }
    
    # catch a directory or file
    function get_file {
        local opt_found=0
        local list_opt=""
        local pkey=""
        
        local fun_text="Choose a file"
        local fun_filename=""
        local fun_filters=""
        local fun_result=""
        
        # 0: zenity; 1: dialog; 2: shell
        local dialog_type=${DIALOG_TYPE}
        local zenity_keys="--file-selection"
        
        # flags
        local flag_dir=0
        
        OPTIND=1
        while getopts ":t:l:f:ds" pkey; do
    
            # verifica se chave já foi chamada
            # excluir chaves que foram chamadas mais de uma vez
            echo "${list_opt}" | grep -q $pkey
            if [ $? -eq 0 ]; then
                syntax "Option -$pkey called twice or more times."
                return 1
            fi
    
            # stored invoked keys
            (( opt_found++ ))
            list_opt="${list_opt};${pkey}"
    
            if [ $opt_found -gt 5 ]; then
                syntax "too many keys"
                return 1
            fi
    
            case "${pkey}" in
                t)
                    fun_text="${OPTARG}"
                    ;;
                f)
                    fun_filename="${OPTARG}"
                    ;;
                l)
                    fun_filters="${OPTARG}"
                    ;;
                d)
                    [ -z "${fun_text}" ] && fun_text="Choose a directory"
                    zenity_keys+=" --directory"
                    flag_dir=1
                    ;;
                s)
                    zenity_keys+=" --save "    
                    ;;    
                \?)
                    syntax "inavalid option: -$OPTARG"
                    return 1
                    ;;
                :)
                    syntax "Option -$OPTARG require argument."
                    return 1
                    ;;
            esac
        done
            
        # zenity_keys+=" --title=\"${fun_text}\" "
        
        if [ -s "${fun_filters}" ]; then
            zenity_keys+=" --file_filter=${fun_filters} "
        fi
        
        if [ -s "${fun_filename}" ]; then
            zenity_keys+=" --filename=${fun_filename} "
        fi
        
        # dialog tool
        if [ $dialog_type -eq 0 ]; then
            fun_result=`zenity --title="${fun_text}" ${zenity_keys}`
            case $? in
            1)
                    echo "No one option selected" >&2
                    return 1
                    ;;
            -1)
                    echo "Error!"
                    return 1
                    ;;
            esac
        else
            syntax "dialog type not implemented."
        fi
        
        echo "${fun_result}"
        return 0
    }
    
    export FILEMAP=""
    export DIRLINK=""
    export LINKNAME=""
    export FLAGTYPE=0
    export TYPEMAP="file"
    export CUR_DIR=`pwd`
    export RETORNO=0
    
    # 
    OPTIND=1
    opt_found=0
    while getopts ":df" pkey; do
        # stored invoked keys
        (( opt_found++ ))
    
        if [ $opt_found -gt 1 ]; then
            syntax_main "too many keys"
            exit 1
        fi
    
        case "${pkey}" in
        d)
             FLAGTYPE=1
             TYPEMAP="directory"
             ;;
        f)
             FLAGTYPE=1
             TYPEMAP="file"
             ;;
        \?)
             syntax_main "invalid key: -$pkey"
             exit 1
             ;;
        esac
    done
    
    # due -d|-f key
    [ $FLAGTYPE -eq 1 ] && shift
    
    # don't change this value!!
    # 0: zenity; 1: dialog; 2: shell
    export DIALOG_TYPE=0
    
    #
    # parameters validation
    #
    [ $# -gt 2 ] && syntax_main "Too many parameters: $#"
    
    # getting file or directory to link
    if [ $# -eq 0 ]; then
        [ $FLAGTYPE -eq 0 ] && TYPEMAP=`dir_or_file` 
        if [ "${TYPEMAP}" = "file" ]; then
            FILEMAP=`get_file -t "Choose any file to link"`
        else
            FILEMAP=`get_file -d -t "Choose any directory to link"`
        fi
    else
        FILEMAP="$1"
    fi 
    
    
    if [ -d "${FILEMAP}" ]; then 
        if [ "${TYPEMAP}" = "file" ]; then
           syntax_main "key set to -f can't link direcory ${FILEMAP}"
        fi
    elif [ -f "${FILEMAP}" ]; then 
        if [ "${TYPEMAP}" = "directory" ]; then
            syntax_main "key set to -d can't link file ${FILEMAP}"
        fi
    else
        syntax_main "Not found or not type regular file or directory: ${FILEMAP}"
        exit 1
    fi
    
    # getting linkname
    if [ $# -lt 2 ]; then
        LINKNAME=`get_file -s -t "Choose the linkname"`
    else
        LINKNAME="${2}"
    fi
    
    # check if ${LINKNAME} already exists file
    if [ -e ${LINKNAME} ]; then  
        if [ -L ${LINKNAME} ]; then
            zenity --question --text="Link ${LINKNAME} already exist. Overwrite it?" --ok-label="Yes" --cancel-label="No"
            if [ $? -ne 0 ]; then
                exit 1 
            fi
        else
            zenity --error --title "error" --text="${LINKNAME} already exist as file or directory"
            exit 1 
        fi    
    fi
    # link
    echo ""
    echo "---------------"
    echo "${TYPEMAP} : ${FILEMAP} "
    echo "link : ${LINKNAME} "
    
    echo ""
    echo "Press a key to continue or [ctrl]+c to exit " ; read
    ln -s -r "${FILEMAP}" "${LINKNAME}"
    [ $? -gt 0 ] && echo "failure!" && exit 1
    
    echo "sucess!"
    exit $RETORNO
    																																																

    public by gwarah modified Jun 23, 2018  1148  2  8  0

    improved cd: <directory pattern> as parameter

    An improvement of cd Linux command. From a given directory pattern, the snippet finds directories matching it and output them as a menu. # Requisites: 1. SHELL=bash 2. locatedb available and up to date. It's necessary to select the directories (see: man (locate | locatedb | updatedb) for more information) # How to use: 1. put this
    #!/bin/bash
    # /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    # * File       : rexcd.sh
    # * Goal       : improve cd linux command
    # * Requisites :
    # *     1. SHELL=bash
    # *     2. Locate service available and up to date. It's necessary to search directories
    # *        (see locate, locatedb and updatedb manual for more information)
    # * History    :
    # *   #version;date;description
    # *   0.1.1; 02/05/2018; tested in ubuntu 16.04/bash and minor code improvements
    # *   0.1.0; 30/04/2018; first release (tested in cygwin 2.10.x)
    # */
    
    # How to use
    #
    # 1. put this script into a directory (Ex: ~/scripts)
    #
    # 2. insert this code in your ~/.bashrc:
    # . ~/scripts/rexcd.sh
    #
    # 3. open a new shell session and test it:
    # cd ~
    # rexcd scripts
    #
    # 4. Example of output (cygwin 2.10.x)
    # Choose one directory
    # 
    # 1) /home/prpe/scripts
    # 2) /home/prpe/sintaxe/scripts_plone
    # 3) /home/prpe/sintaxe/scripts_plone/scripts
    # 4) /usr/share/doc/xorg-scripts-1.0.1
    # 5) /usr/x86_64-pc-cygwin/lib/ldscripts
    # Option [1] 2
    # 
    #  
    # prpe@DESK-00-090117 ~/sintaxe/scripts_plone
    # $
    
    
    #
    # ToDo:
    #
    # 1. switch:-i (ignore case)
    # 2. switch:-l limits of directories in menu (from m-th to n-th search matches)  (m,n|m,|,n default 1 to number of matches)
    # 3. switch:-d root directory -d <dir> (default /)
    # 4. switch:-u perform an update of db table
    #
    
    # syntax: rexcd_exit <msg>
    function rexcd_exit {
        local msg=$1
        echo "${msg}" >&2
        return 1
    }
    
    # syntax: 
    #  export rexcd_opt=""
    #  rexcd_menu opt1 opt2 ... optn
    #  echo $rexcd_opt
    function rexcd_menu {
        # return code + option
        local FN_RESULT=1
        rexcd_opt=""
    
        # variáveis de controle
        local num_options=$#
        local arr_options
        local num_choose=1
        local FN_DEFAULT=""
        local v_aux1 v_aux2
        local fl ind
    
        # menu message
        local FN_MSG="Choose one directory "
        local PS3="#"
    
        # checking number of options and creating list of them
        if [ $num_options -lt 2 ]; then
            rexcd_exit "At least 2 options required"
            return $?
        fi
    
        let ind=1
        for fl in $*; do
            arr_options[${ind}]="${fl}"
            let ind++
        done
    
        # menu
        FN_RESULT=1
        ind=1
        num_choose=""
        FN_DEFAULT=$ind
        PS3="Option [${FN_DEFAULT}] "
        
        echo "" ; echo "${FN_MSG}" ; echo ""
        select num_choose in `echo ${arr_options[@]}`; do
            case "${num_choose}" in
                *)
                    if [ -z "${num_choose}" ]; then
                        read -t 2 -p "Invalid option"
                        echo "" ; echo "${FN_MSG}" ; echo ""
                        continue
                    fi
                    FN_RESULT=0
                    break
                    ;;
            esac
        done
        echo ""
    
        rexcd_opt="${num_choose}"
        return ${FN_RESULT}
    }
    
    function rexcd {
        local contador fl
        local padrao=""
        local max_opc=15
        local lst_opc=""
        local retorno=0
        local v_aux=0
    
        # its necessary declare as export
        export rexcd_opt=""
    
        if [ $# -ne 1 ]; then
            rexcd_exit "Number of arguments invalid: $#. Must be exactly one."
            return $?
        fi
    
        padrao=$1
        contador=0
        cd /
        for fl in `locate -i "${padrao}"`; do
            # filter not directories elements
            [ ! -d "${fl}" ] && continue
    
            # search regards
            basename "${fl}" | grep -q -i "${padrao}"
            [ $? -ne 0 ] && continue
    
    
            # update array e var count
            let v_aux=contador+1
    
            if [ $contador -eq 1 ]; then
                lst_opc="${fl}"
            else
                lst_opc="${lst_opc} ${fl}"
            fi
    
            let contador++
            # verifica o máximo de entrada
            if [ $contador -ge $max_opc ]; then
                echo "WARNING: Maximum number of options $max_opc reached" >&2
                break
            fi
        done
    
        if [ ${contador} -eq 1 ]; then
            rexcd_opt="${lst_opc}"
        elif [ ${contador} -gt 1 ]; then
            export rexcd_opt=""
            rexcd_menu ${lst_opc}
            retorno=$?
        else
            rexcd_exit "No directory matches with ${padrao}."
            retorno=$?
        fi
    
        [ $retorno -eq 0 ] && cd ${rexcd_opt}
        return ${retorno}
    }
    																														

    List Complete ( 5 snippets total )

    • Public Snippets
    • Channels Snippets