Oct
19
2013
Previously… Useful bash functions
This new version is a tad more efficient since there are no more echo and pipes involved on the processing. Just one eval and one awk script.
1
2
3
4
5
6
7
8
9
10
11
12 unique_path() {
eval $(awk -v VAR="${1}" 'BEGIN { \
if((N=split(ENVIRON[VAR],vals,":"))<2) exit(0); \
sep = out="" ; i=split(out,seen); \
do { if(!(vals[++i] in seen)) { seen[vals[i]]; \
gsub("["]","\\"",vals[i]); \
out=sprintf("%s%s%s",out,sep,vals[i]); \
sep=":"; \
} } while (i<N); \
printf "%s="%s"; export %s;\n",VAR,out,VAR; \
}' /dev/null)
}
Similarly, these also had remove unnecessary uses of sub-shell echo…
1
2
3
4
5
6
7
8
9
10
11 safe_prepend_path() {
VAR=$1 ; shift ; eval VAL=\$${VAR}
for i_;do [ -d "$i_" ] && VAL=$i_${VAL:+":$VAL"} ;done
eval export ${VAR}=${VAL}
}
safe_append_path() {
VAR=$1 ; shift ; eval VAL=\$${VAR}
for i_;do [ -d "$i_" ] && VAL=${VAL:+"$VAL:"}$i_ ;done
eval export ${VAR}=${VAL}
}
Leave a Reply
You must be logged in to post a comment.