#!/bin/bash # Author: Christian Birchinger # # What: Apply filetype highlighting using LS_COLORS env variable # TODO: More error handling (like LS_COLORS existing), while # keeping the loops as efficient and fast as possible. # # Examples: ~$ locate some_string | ls_color # ~$ find "$HOME" -maxdepth 1 | ls_color IFS=':' read -ra cols <<< "$LS_COLORS" declare -A lsc declare -A lscbi for col in "${cols[@]}"; do colk=${col%%=*} if [[ "$colk" =~ ^(rs|di|ln|mh|pi|so|do|bd|cd|or|mi|su|sg|ca|tw|ow|st|ex)$ ]]; then lscbi["${colk}"]="${col##*=}" else lsc["${colk}"]="${col##*=}" fi done while IFS= read -r input; do if [[ $input == */* ]]; then file=${input##*/} dir=${input%/*} echo -ne "\e[${lscbi["di"]}m${dir}/\e[${lscbi["rs"]}m" else file=$input dir='' fi if [[ -L ${input} ]]; then echo -e "\e[${lscbi["ln"]}m${file}\e[${lscbi["rs"]}m" elif [[ -d ${input} ]]; then echo -e "\e[${lscbi["di"]}m${file}\e[${lscbi["rs"]}m" elif [[ -x ${input} ]]; then echo -e "\e[${lscbi["ex"]}m${file}\e[${lscbi["rs"]}m" else matched=0 for t in "${!lsc[@]}"; do # shellcheck disable=SC2053 # $t contains globing patterns if [[ "${file}" == $t ]]; then echo -e "\e[${lsc["${t}"]}m${file}\e[${lscbi["rs"]}m" matched=1 break fi done [[ $matched -eq 0 ]] && echo "$file" fi done