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