Code challenge: Bash prompt path shortener

前端 未结 5 1388
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 09:27

I implemented a prompt path shortener for bash to be included in the PS1 environment variable, which shortens the working directory into something more compact but still descrip

5条回答
  •  深忆病人
    2021-01-30 10:18

    Another solution with only bash internals, no use of sed

    shortpath()                                                                                                                                                                                                                                                                   
    {           
        dir=${1%/*} && last=${1##*/}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
    
        res=$(for i in ${dir//\// } ; do echo -n "${i:0:3}../" ; done)                                                                                                                                                                                                            
        echo "/$res$last"                                                                                                                                                                                                                                                         
    } 
    

    My previous solution, with bash and sed. it cut each dir in 3 first caracters and add '..' like this: /hom../obo../tmp../exa../bas../

    shortpath()
    {
            dir=$(dirname $1)
            last=$(basename $1)
    
            v=${dir//\// } # replace / by  in path
            t=$(printf "echo %s | sed -e 's/^\(...\).*$/\\\1../' ; " $v) 
                # prepare command line, cut names to 3 char and add '..'
            a=$(eval $t) 
                # a will contain list of 3 char words ended with '..' ans separated with ' '
    
            echo " "$a"/"$last | sed -e 's/ /\//g'
    }
    

提交回复
热议问题