an alias for cherry-pick
[dotfiles] / .bash_function
1 #!/bin/sh
2 # my weird function file
3 # lots of this coming from http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming
4
5 my_whois_onport(){
6 # return the service on port
7 local port=$1
8 sudo lsof -i :$port
9 }
10
11 my_mount_set_of_partition(){
12 # Mount set of partitions for recovery.
13 for i in {1..12}; do
14 mkdir /media/sdd$i && mount -o ro /{dev,media}/sdd$i || rmdir /media/sdd$i ;
15 done
16 }
17
18 my_copy_file_to_clipboard() {
19 local filecontent=$1
20 [ -f $file ] && xclip -sel clip < $filecontent
21 }
22
23 my_usage() {
24
25 cat <<-EOF
26 usage: $PROGNAME options
27
28 Program deletes files from filesystems to release space.
29 It gets config file that define fileystem paths to work on, and whitelist rules to
30 keep certain files.
31
32 OPTIONS:
33 -c --config configuration file containing the rules. use --help-config to see the syntax.
34 -n --pretend do not really delete, just how what you are going to do.
35 -t --test run unit test to check the program
36 -v --verbose Verbose. You can specify more then one -v to have more verbose
37 -x --debug debug
38 -h --help show this help
39 --help-config configuration help
40
41
42 Examples:
43 Run all tests:
44 $PROGNAME --test all
45
46 Run specific test:
47 $PROGNAME --test test_string.sh
48
49 Run:
50 $PROGNAME --config /path/to/config/$PROGNAME.conf
51
52 Just show what you are going to do:
53 $PROGNAME -vn -c /path/to/config/$PROGNAME.conf
54
55 EOF
56 }
57
58 my_change_owner_of_files() {
59 local user=$1; shift
60 local group=$1; shift
61 local files=$@
62 local i
63
64 for i in $files
65 do
66 chown $user:$group $i
67 done
68 }
69
70
71 my_template_function() {
72 # local vars
73 local PROGNAME=$(basename $0)
74 local PROGDIR=$(readlink -m $(dirname $0))
75 local ARGS="$@"
76 local first_arg=$1
77
78 # readonly var
79 #readonly local second_arg=$2;
80
81 # if no args, print usage
82 is_empty_string $ARGS && my_usage
83
84
85 }
86
87 my_list_venv(){
88 ls $HOME"/envs"
89 }
90
91 my_goto_venv() {
92 local dir=$1
93 local env=$HOME"/envs/"$dir"/source/"
94 #if source dir not exists, create & cd
95 [ -d $env ] && cd $env || mkdircd -p $env
96 # activate virtualenv
97 source $HOME"/envs/"$dir"/bin/activate"
98 }
99
100 # Taken from http://aaroncrane.co.uk/2009/03/git_branch_prompt/
101 find_git_repo() {
102 local dir=.
103 until [ "$dir" -ef / ]; do
104 if [ -f "$dir/.git/HEAD" ]; then
105 GIT_REPO=`readlink -e $dir`/
106 return
107 fi
108 dir="../$dir"
109 done
110 GIT_REPO=''
111 return
112 }
113
114 find_git_branch() {
115 head=$(< "$1/.git/HEAD")
116 if [[ $head == ref:\ refs/heads/* ]]; then
117 GIT_BRANCH=${head#*/*/}
118 elif [[ $head != '' ]]; then
119 GIT_BRANCH='(detached)'
120 else
121 GIT_BRANCH='(unknown)'
122 fi
123 }
124
125 # Taken from https://github.com/jimeh/git-aware-prompt
126 find_git_dirty() {
127 local status=$(git status --porcelain 2> /dev/null)
128 if [[ "$status" != "" ]]; then
129 GIT_DIRTY='*'
130 else
131 GIT_DIRTY=''
132 fi
133 }
134
135 find_git_stash() {
136 if [ -e "$1/.git/refs/stash" ]; then
137 GIT_STASH='stash'
138 else
139 GIT_STASH=''
140 fi
141 }
142
143 cdls() { cd "$@" && clear && ls; }
144
145
146 cl(){
147 if [ -d "$1" ]; then
148 cd "$1"
149 clear
150 ls -lh
151 else
152 cd
153 clear
154 ls
155 fi
156 }
157
158
159 mkdircd(){
160 mkdir -p "$@" && eval cd "\"\$$#\"";
161 }
162
163 my_emacs_servers(){
164 local serverdir="${TMPDIR:-/tmp}/emacs${UID}"
165 local -a servers
166 for file in ${serverdir}/*; do
167 if [[ -S ${file} ]]; then
168 servers+=("${file##*/}")
169 fi
170 done
171
172 echo "${servers[@]}"
173 }
174
175 my_fib(){
176 x=${1:-1}
177 y=${2:-1}
178 echo $(($x + $y))
179 fib $y $(($x + $y))
180 }
181
182
183 my_recursiveFibo() {
184 local start=0;
185 n="$1";
186 inc="$2";
187 while ((n < $inc));
188 do
189 result=$((start+n));
190 start=$n;
191 n="$result";
192 printf '%s ' "$result";
193 done;
194 }
195
196 #recursivFibo 1 2048
197
198 my_err() {
199 echo "[$(date + '%Y-%m-%dT%H:%M:%S%z')]: $@ >&2"
200 }
201
202 my_test() {
203 echo 'test';
204 }
205
206 my_test2(){
207 if my_test; then
208 my_err "unable to my_test"
209 exit "${E_DID_NOTHING}"
210 fi
211 }
212
213 my_pretty_print_json() {
214 python -m json.tool
215 }
216
217 my_not_start_service_on_boot(){
218 # service to not start on boot
219 local service=$1;
220 update-rc.d $service disable;
221 }
222
223 my_install_new_font(){
224 #sudo fc-cache -v -f
225 fc-cache -v -f;
226 }
227
228 my_launch_eth0(){
229 # set eth0 iface up
230 sudo ip link set eth0 up;
231 # ask for an ip via dhcp
232 sudo dhclient eth0;
233 }
234
235 #function to show the current branch
236 my_show_current_branch(){
237 git rev-parse --abbrev-ref HEAD
238 }
239
240 my_pdf_nbpages(){
241 local filename=$1;
242
243 echo $(pdftk $filename dump_data \
244 | grep -i numberofpages \
245 | awk '{print $2}');
246 }
247
248 my_pdf_explosion() {
249 local filename=$1;
250 echo $(pdftk $filename burst);
251 }
252
253 my_pdfs_to_xml() {
254 for i in $(ls | grep .pdf$); do
255 pdftohtml -xml $i;
256 done;
257 }
258
259 # function to show one line of file
260 my_xline_of_file(){
261 local line_number=$1;
262 local filename=$2;
263 local p='p';
264
265 echo $(sed -n $line_number$p $filename);
266 }
267
268 # function to extract in one command
269 my_xtract() {
270 local filename=$1;
271
272 if is_file $filename ; then
273 case $filename in
274 *.tar.xz) tar xvfJ $filename ;;
275 *.xz) tar xf $filename ;;
276 *.tar.bz2) tar xvjf $filename ;;
277 *.tar.gz) tar xvzf $filename ;;
278 *.bz2) bunzip2 $filename ;;
279 *.rar) unrar x $filename ;;
280 *.gz) gunzip $filename ;;
281 *.tar) tar xvf $filename ;;
282 *.tbz2) tar xvjf $filename ;;
283 *.tgz) tar xvzf $filename ;;
284 *.zip) unzip $filename ;;
285 *.Z) uncompress $filename ;;
286 *.7z) 7z x $filename ;;
287 *) echo "'$filename' cannot be extracted via extract" ;;
288 esac
289 else
290 echo "'$filename' is not a valid file"
291 fi
292 }
293
294 # function to list the content of an archive
295 my_list_archive_content() {
296 local filename=$1;
297
298 if is_file $filename ; then
299 case $filename in
300 *.tar.xz) tar tvfJ $filename ;;
301 *.tar.bz2) tar tvjf $filename ;;
302 *.tar.gz) tar tzvf $filename ;;
303 *.bz2) bunzip2 $filename ;;
304 *.gz) gunzip -l $filename ;;
305 *.tar) tar tvf $filename ;;
306 *.tbz2) tar tvjf $filename ;;
307 *.tgz) tar tvzf $filename ;;
308 *.zip) unzip -l $filename ;;
309 *.Z) uncompress -l $filename ;;
310 *.7z) 7z l $filename ;;
311 *) echo "content of '$filename' cannot be listed :(" ;;
312 esac
313 else
314 echo "'$filename' is not a valid file"
315 fi
316 }
317
318 # dump a mysql database
319 my_dump_mysql_db() {
320 local database=$1;
321
322 echo "dumping database '$database' ..."
323 mysqldump -u patrick -ppatrick $database > $databse_dump_$(date +%m%d%Y).sql
324
325 }
326
327 my_dump_mysql_table() {
328 local database=$1;
329 local table=$2;
330
331 echo "dumping table '$table' from database '$database' ..."
332 mysqldump -u patrick -ppatrick $database $table > $table_dump_$(date +%m%d%Y).sql
333 }
334
335 my_uploadfile() {
336 local filename=$1
337 local ftp_url=$2;
338 local user=$3;
339 local password=$4;
340
341 echo "upload of '$filename' to '$ftp_url' by '$user' ..."
342 #curl -T $filename ftp://dev.africafilms.tv/movies/ --user dev.africafilms.tv:dev/aftv/DAK2602
343 curl -T $filename $ftp_url --user $user:$password
344 }
345
346 my_find_string() {
347 local string_to_find=$1;
348 local directory=$2;
349
350 echo "recursive looking for the string '$string' inside '$directory' directory"
351 grep -l -R -i -r $string_to_find $directory;
352 }
353
354 my_find_string2() {
355 local string_to_find=$1;
356 local directory=$2;
357
358 echo "recursive looking for the string '$string' inside '$directory' directory"
359 find $directory | xargs grep $string -sl;
360
361 }
362 # extract md5 hash from a string
363 my_xmd5() {
364 local string=$1;
365
366 echo "md5 hash of '$string' is: "
367 echo -n "$string" | md5sum;
368 }
369
370 # Creates an archive (*.tar.gz) from given directory.
371 my_maketar() {
372 local directory=$1;
373
374 tar cvzf "${directory%%/}.tar.gz" "${directory%%/}/";
375 }
376
377 # Create a ZIP archive of a file or folder.
378 my_makezip() {
379 local file=$1;
380
381 zip -r "${file%%/}.zip" "$file";
382 }
383
384 # Make your directories and files access rights sane.
385 my_sanitize() { chmod -R u=rwX,g=rX,o= "$@" ;}
386
387 # Get IP adress on ethernet.
388 my_ip() {
389 local my_ip=$( /sbin/ifconfig eth0 \
390 | awk '/inet/ { print $2 } ' \
391 | sed -e s/addr://);
392 local my_gtw="gtw: "$(netstat -nr | awk '{print $2}' | sed -n 3p);
393 echo ${my_ip:-"Not connected"}
394 echo ${my_gtw:-"Not connected"}
395 }
396
397 # Get current host related info.
398 my_host_info() {
399 echo -e "\nYou are logged on ${BRed}$HOST"
400 echo -e "\n${BRed}Local IP Address :$NC" ; my_ip
401 echo -e "\n${BRed}Current date :$NC " ; date; calendar | head -1
402 echo -e "\n${BRed}Additionnal information:$NC " ; uname -a
403 echo -e "\n${BRed}Users logged on:$NC " ; \
404 w -hs \
405 | cut -d " " -f1 \
406 | sort \
407 | uniq
408 echo -e "\n${BRed}Machine stats :$NC " ; uptime
409 echo -e "\n${BRed}Memory stats :$NC " ; free -h
410 echo -e "\n${BRed}Diskspace :$NC " ; mydf / $HOME
411 echo -e "\n${BRed}Open connections :$NC "; netstat -pan --inet;
412 echo
413 }
414
415 # Pretty-print of 'df' output. Inspired by 'dfc' utility.
416 my_df() {
417 local fs=$1;
418
419 for fs ; do
420
421 if [ ! -d $fs ]
422 then
423 echo -e $fs" :No such file or directory" ; continue
424 fi
425
426 local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') )
427 local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') )
428 local nbstars=$(( 20 * ${info[1]} / ${info[0]} ))
429 local out="["
430 for ((j=0;j<20;j++)); do
431 if [ ${j} -lt ${nbstars} ]; then
432 out=$out"*"
433 else
434 out=$out"-"
435 fi
436 done
437 out=${info[2]}" "$out"] ("$free" free on "$fs")"
438 echo -e $out
439 done
440 }
441
442 # create_vm(){
443 # debootstrap --verbose \
444 # --variant=minbase \
445 # --arch=i386 --include ifupdown,locales,libui-dialog-perl,dialog,dhcp3-client,netbase,net-tools,iproute,openssh-server \
446 # sid /var/lib/lxc/sid http://ftp.debian.org/debian
447
448 # }
449
450
451 my_add_todo(){
452 local rememberfile="$HOME/.remember"
453 # if the file not exists, touch it
454 [[ ! -f $rememberfile ]] && touch $rememberfile
455 if [ $# -eq 0 ] ; then
456 echo "Type what you want to remember then, hit ^D: "
457 cat - >> $rememberfile;
458 else
459 #echo $(date +%m%d%Y)" -- $@" >> $rememberfile
460 echo $(date +%F)" -- $@" >> $rememberfile
461 fi
462 }
463
464 my_reminder(){
465 local rememberfile="$HOME/.remember"
466
467 #is_not_file $remberfile && echo 'nothing to do' ||
468 #is_empty $rememberfile && echo 'nothing to do' ||
469 #display_todo "$@"
470 is_not_file $rememberfile || [[ $(cat $rememberfile | wc -l) = 0 ]] && echo "nothing to do" || my_display_todo "$@";
471 }
472
473 my_display_todo(){
474
475 local rememberfile="$HOME/.remember"
476 echo $#;
477 #[[ $# -eq 0 ]] && more $rememberfile || grep -i "$@" $rememberfile | more;
478 [[ $# -eq 0 ]] && is_file $rememberfile && is_not_empty_file $rememberfile && cat $rememberfile || grep -i "$@" $rememberfile;
479 }
480
481
482 my_lsbytesum() {
483 #lsbytesum - sum the number of bytes in a directory listing
484 TotalBytes=0
485 for Bytes in $(ls -l | grep "^-" | awk '{ print $5 }')
486 do
487 let TotalBytes=$TotalBytes+$Bytes
488 done
489 TotalMeg=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc)
490 echo -n "$TotalMeg"
491 }
492
493 # list
494 my_create_list(){
495 local listname=$1;
496 declare -a $listname;
497 }
498
499 # sensonet
500
501 sensonet_create_event() {
502 curl -i -X "POST" -k -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Accept: application/json" -d "name=$1" http://projects.emerginov.orange.sn/sensonet/resources/events/"$2"
503 }
504
505 sensonet_update_event() {
506 curl -i -X "PUT" -k -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Accept: application/json" -d "name=$1" http://projects.emerginov.orange.sn/sensonet/resources/events/"$2"
507 }
508
509 sensonet_events() {
510 [[ $# -eq 0 ]] && curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/events/ || \
511 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/events/"$1"
512 }
513
514 sensonet_del_event() {
515 curl -i -X "DELETE" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/events/"$1"
516 }
517
518 sensonet_create_sensor() {
519 curl -i -X "POST" -k -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Accept: application/json" -d "description=$1" http://projects.emerginov.orange.sn/sensonet/resources/sensors/"$2"
520 }
521
522 sensonet_update_sensor() {
523 curl -i -X "PUT" -k -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Accept: application/json" -d "description=$1" http://projects.emerginov.orange.sn/sensonet/resources/sensors/"$2"
524 }
525
526 sensonet_del_sensor() {
527 curl -i -X "DELETE" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/sensors/"$1"
528 }
529
530 sensonet_sensors() {
531 [[ $# -eq 0 ]] && curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/sensors/ || \
532 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/sensors/"$1"
533 }
534
535 sensonet_create_network(){
536 curl -i -X "POST" -k -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" -d "name=$1" http://projects.emerginov.orange.sn/sensonet/resources/networks/"$2"
537 }
538
539 sensonet_update_network(){
540 curl -i -X "PUT" -k -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" -d "name=$1" http://projects.emerginov.orange.sn/sensonet/resources/networks/"$2"
541 }
542
543 sensonet_del_network(){
544 curl -i -X "DELETE" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/networks/"$1"
545 }
546
547 sensonet_networks(){
548 [[ $# -eq 0 ]] && curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/networks/ || \
549 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/networks/"$1"
550 }
551
552 sensonet_network_probes() {
553 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/networks/"$1"/probes
554 }
555
556 sensonet_create_probe() {
557 curl -i -X "POST" -k -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" \
558 -d "name=${1}&latitude=0.0&longitude=0.0&monitorMe=1&sleepingTime=0&networkId=univlab" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${2}"
559 }
560
561 sensonet_update_probe() {
562 curl -i -X "PUT" -k -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" \
563 -d "name=${1}&latitude=48.0&longitude=-1.0&monitorMe=1&sleepingTime=0" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${2}"
564 }
565
566 sensonet_probes() {
567 [[ $# -eq 0 ]] && curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/ || \
568 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${1}"
569 }
570
571 sensonet_del_probe() {
572 curl -i -X "DELETE" -k -H -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${2}"
573 }
574
575 sensonet_probe_neighborhood(){
576 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${1}"/neighborhood
577 }
578
579 sensonet_probe_set_sleeping_time(){
580 curl -i -X "POST" -k -H "Content-Type: application/x-www-form-urlencoded" -H "Accept: application/json" -d "duration=${2}" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${1}"/sleepingtime
581 }
582
583 sensonet_probe_sensors(){
584 [[ $# -eq 1 ]] && curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${1}"/sensors || \
585 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${1}"/sensors/"${2}"
586 }
587
588 sensonet_probe_sensor_values(){
589 curl -i -X "GET" -k -H "Accept: application/json" http://projects.emerginov.orange.sn/sensonet/resources/probes/%2B221"${1}"/sensors/"${2}"/values
590 }
591
592 # from nixcraft
593 # Show top 10 history command on screen
594 function ht {
595 history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head
596 }
597
598 # Wrapper for host and ping command
599 # Accept http:// or https:// or ftps:// names for domain and hostnames
600 _getdomainnameonly(){
601 local h="$1"
602 local f="${h,,}"
603 # remove protocol part of hostname
604 f="${f#http://}"
605 f="${f#https://}"
606 f="${f#ftp://}"
607 f="${f#scp://}"
608 f="${f#scp://}"
609 f="${f#sftp://}"
610 # remove username and/or username:password part of hostname
611 f="${f#*:*@}"
612 f="${f#*@}"
613 # remove all /foo/xyz.html*
614 f=${f%%/*}
615 # show domain name only
616 echo "$f"
617 }
618
619
620 ping(){
621 local array=( $@ ) # get all args in an array
622 local len=${#array[@]} # find the length of an array
623 local host=${array[$len-1]} # get the last arg
624 local args=${array[@]:0:$len-1} # get all args before the last arg in $@ in an array
625 local _ping="/bin/ping"
626 local c=$(_getdomainnameonly "$host")
627 [ "$t" != "$c" ] && echo "Sending ICMP ECHO_REQUEST to \"$c\"..."
628 # pass args and host
629 $_ping $args $c
630 }
631
632 host(){
633 local array=( $@ )
634 local len=${#array[@]}
635 local host=${array[$len-1]}
636 local args=${array[@]:0:$len-1}
637 local _host="/usr/bin/host"
638 local c=$(_getdomainnameonly "$host")
639 [ "$t" != "$c" ] && echo "Performing DNS lookups for \"$c\"..."
640 $_host $args $c
641 }