• MonkderVierte@lemmy.ml
    link
    fedilink
    arrow-up
    11
    ·
    edit-2
    4 months ago

    Oneliner functions count too, right?

    binexist() {
    	##: lookup input in PATH, returns bool true/false
    #	IFS=:; find $PATH -executable -name "$1" 2>/dev/null |grep -q "/$1$" # slower
    	command -v "$1" >/dev/null 2>&1
    }
    contains() {
    	##: finds term in string, returns true/false
    	##: $ contains <search term> <string>
    	case "$1" in *${2}*) return 0;; *) return 1;; esac
    }
    
    error() {
           ##: complain to STDERR and exit if given code 
            printf '%s\n' "$1" >&2; [ -n "$2" ] && exit "$2"
    }
    
    random() {
    	##: generate random number of <input> length
    	test "$1" -gt 1 && shuf -i 0-9 -n"$1" |tr -d '\n'
    }
    
    nfoview() {
    	##: view nfo files like intended
    	iconv -f CP866 <"$1" |less
    }
    
    mod_preset() {
    	##: print a nicely formatted preset of module options
    	modinfo -p "$1" |awk \
    		-F':' \
    		-v 'module="$1"' \
    		'{first=$1; $1="";print "\n#"$0"\n#options module "first"="}'
    }
    
    dpv() {
    	##: flash image to stick with progress bar, workaround for pv's flash bug #oflag=direct is fastest
    	##: https://askubuntu.com/questions/901481/writing-to-disk-using-pv-seems-to-be-fast-at-first-and-slow-at-the-end/961659#961659
    	pv "$1" |pkexec dd of="$2" bs=4M oflag=direct iflag=fullblock
    }
    

    Not oneliners but still something i want to show off:

    functions() {
    	##: prints code of function files
    	function_s="$(sed '/^$/d;/##[^:]/d' "$SHELL_HOME"/functions)"
    	if [ -n "$1" ]
    		then echo "$function_s" |sed -n -e "/$1.*{/,/^}/ p" |highlight --line-numbers -qs candy --out-format=xterm256 --syntax=sh --stdout
    		else echo "$function_s" |highlight -qs candy --out-format=xterm256 --syntax=sh --stdout
    	fi
    }
    
    readconf() {
    	# reads parameters from config file in param=value note, where '=' is set with $separator
    	# format: conf_read <parameter> <replacement> where replacement get's used if parameter is empty
    	if [ -f "$cfg_file" ]
    		then parm="$(cut -d'#' -f1 "$cfg_file" |grep "$1" |cut -d${separator} -f2- |tr -d '"')"
    		else unset parm; fi
    	[ "$separator" = "=" ] && printf '%s\n' "${parm:-"$2"}"
    }
    

    The readconf function is used like this:

    config content:
    # this a comment
    apple=red
    banana=yellow # this too
    
    config=/path/to/config.conf
    $ color_apple="$(readconf apple green)"
    $ color_banan="$(readconf banana)"
    

    And the ‘functions’ function looks like this: