forked from anishathalye/dotfiles_template
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalias
More file actions
executable file
·1636 lines (1384 loc) · 59.4 KB
/
alias
File metadata and controls
executable file
·1636 lines (1384 loc) · 59.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[ -f ~/.env ] && source ~/.env
[ -f ~/.env_private ] && source ~/.env_private
[ -f ~/.alias.nixos ] && source ~/.alias.nixos
unalias fd >/dev/null 2>/dev/null # in order to use https://github.com/sharkdp/fd
alias mintupdate='sudo mintupdate-cli --install-recommends -y upgrade'
##########################
# DOTFILES UPDATE
##########################
alias dotfiles_update='cd $DOTFILES_PATH && git pull && bash install; cd -'
##########################
# UPDATE AppImages
##########################
# https://github.com/nextcloud/desktop/issues/7231
alias update_nextcloud="wget https://download.nextcloud.com/desktop/releases/Linux/latest -O $HOME/bin/Nextcloud.AppImage && chmod +x $HOME/bin/*.AppImage"
#alias update_nextcloud="wget https://download.nextcloud.com/desktop/releases/Linux/Nextcloud-3.13.4-x86_64.AppImage -O $HOME/bin/Nextcloud.AppImage && chmod +x $HOME/bin/*.AppImage"
alias update_joplin='curl -s https://api.github.com/repos/laurent22/joplin/releases/latest | grep "browser_download_url.*AppImage" | cut -d : -f 2,3 | tr -d \" | head -1| wget --show-progress -qi - -O $HOME/bin/Joplin.AppImage && chmod +x $HOME/bin/*.AppImage'
alias update_etcher='curl -s https://api.github.com/repos/balena-io/etcher/releases/latest | grep "browser_download_url.*x64.AppImage" | cut -d : -f 2,3 | tr -d \" | wget --show-progress -qi - -O $HOME/bin/balenaEtcher.AppImage && chmod +x $HOME/bin/*.AppImage'
alias update_shotcut='curl -s https://api.github.com/repos/mltframework/shotcut/releases/latest | grep "browser_download_url.*AppImage" | cut -d : -f 2,3 | tr -d \" | wget --show-progress -qi - -O $HOME/bin/Shotcut.AppImage && chmod +x $HOME/bin/*.AppImage'
alias update_appimages='update_nextcloud; update_joplin; update_etcher; update_shotcut'
alias shotcut='Shotcut.AppImage --QT_SCALE_FACTOR 1'
alias Shotcut='shotcut'
##########################
# ls and cd aliases
##########################
# quick way to get out of current directory
alias ..='cd ..'
alias ...='cd ../../../'
alias ....='cd ../../../../'
alias .....='cd ../../../../../'
alias .5='cd ../../../../..'
alias cc='ls -f | wc -l' # ls -f does not stat() and makes it faster
path_to_lsd=$(which lsd 2>/dev/null)
if [ -x "$path_to_lsd" ] ; then
alias ls='lsd'
alias l='ls -l'
alias ll='ls -l'
alias la='ls -a'
alias lla='ls -la'
alias lt='ls --tree'
fi
if command -v ag >/dev/null 2>&1; then
alias ag='ag --hidden'
fi
##########################
# CHEF cooking + Ansible provisionning
##########################
alias chef_cd="cd $CHEF_DIR"
alias chef_private_cd="cd $CHEF_DIR/../chef-private"
alias talend="chef_cd && ./bin/talend7-pipeline.sh"
alias chef_imos="chef_cd && rm -f private; ln -s ../chef-private private"
alias chef_pipeline_box_start="chef_cd && ./bin/write_pipeline_stack_secrets.sh -p nodes/pipeline.json; ./bin/pipeline-box.sh"
alias chef_pipeline_box_provision="chef_cd && ./bin/write_pipeline_stack_secrets.sh -p nodes/pipeline.json; vagrant provision pipeline"
alias chef_sample="chef_cd && rm -f private; ln -s private-sample private"
#alias vagrant_ssh='var=$(find $CHEF_DIR/nodes/ -type f -name "*\.json" -exec basename {} \; | cut -d . -f 1 | fzf) && cd $CHEF_DIR && vagrant ssh $var'
function vs(){
#List all vagrant boxes available in the system including its status, and try to access the selected one via ssh
cd $(cat ~/.vagrant.d/data/machine-index/index | jq '.machines[] | {name, vagrantfile_path, state}' | jq '.name + "," + .state + "," + .vagrantfile_path'| sed 's/^"\(.*\)"$/\1/'| column -s, -t | sort -rk 2 | fzf | awk '{print $3}'); vagrant ssh
}
alias vagrant_ssh=vs
#alias chef_pipeline_bckp_json='cp $CHEF_DIR/private-sample/nodes/pipeline.json $CHEF_DIR/private-sample/nodes/pipeline.json.bckp'
#alias chef_pipeline_restore_json='cp $CHEF_DIR/private-sample/nodes/pipeline.json.bckp $CHEF_DIR/private-sample/nodes/pipeline.json'
alias ansible_provision_latop='ansible-playbook -i hosts $ANSIBLE_PATH/local.yml -K'
alias ansible_provision_remote='ansible-playbook -i hosts $ANSIBLE_PATH/remote.yml'
[[ `hostname` == "9-aws-syd" ]] && alias stackman="source /opt/stackman/virtualenv__usr_bin_python3/bin/activate;stackman";
[[ `hostname` == "po-dev-aws-syd" ]] && alias stackman="source /mnt/ebs/pyenv/versions/3.8.10/envs/commandpost_venv/bin/activate;stackman";
##########################
# IMOS related - pipeline
##########################
alias project_officer_user='sudo -u projectofficer -s'
# pipeline
export PIPELINE_TASK_LOG_PATH=/mnt/ebs/log/pipeline/process
# add ~/.zsh_functions to fpath, and then lazy autoload
# every file in there as a function. THIS IS A REQUIREMENT
fpath=(~/.zsh_functions $fpath);
if command -v autoload > /dev/null; then
autoload -U ${fpath[1]}/*(N-.:t)
fi
# For multiple functions files, just source them
source $HOME/.zsh_functions/imos_ardc.zsh
source $HOME/.zsh_functions/pipelines.zsh
source $HOME/.zsh_functions/comics.zsh
# wget for imos buck by simply giving the relative path of an object without the full bucket address
# $1 imos bucket url
# $2 output_folder (optional)
wget_imos_bucket() {
local url_suffix=$1; shift;
local url_prefix="https://s3-ap-southeast-2.amazonaws.com/imos-data/"
local output_folder=$1;
[ ! -z $output_folder ] && wget ${url_prefix}${url_suffix} || \
wget -P $output_folder ${url_prefix}${url_suffix}
}
if [[ -d ~/.local/share/JetBrains/Toolbox/apps/ ]]; then
alias pycharm=`fd pycharm.sh ~/.local/share/JetBrains/Toolbox/apps/ &`
fi
function aws_select_profile() {
# Define local variables
local profiles
local selected_profile
# Read the content of the ~/.aws/config file and extract profile names
profiles=$(awk '$1=="[profile" {print substr($2, 1, length($2)-1)}' ~/.aws/config)
# Use fzf to select a profile
selected_profile=$(echo "$profiles" | fzf)
# Export AWS_PROFILE with the selected profile
export AWS_PROFILE="$selected_profile"
# Optionally, you can print the selected profile for confirmation
echo "Selected AWS profile: $selected_profile"
}
function aws_select_profile_login() {
# Define local variables
local profiles
local selected_profile
# Read the content of the ~/.aws/config file and extract profile names
profiles=$(awk '$1=="[profile" {print substr($2, 1, length($2)-1)}' ~/.aws/config)
# Use fzf to select a profile
selected_profile=$(echo "$profiles" | fzf)
# Export AWS_PROFILE with the selected profile
export AWS_PROFILE="$selected_profile"
aws sso login --profile $AWS_PROFILE --no-browser --use-device-code
# Optionally, you can print the selected profile for confirmation
echo "Selected AWS profile: $selected_profile"
}
function aws_okta_forward_port() {
if [ -z "$1" ]; then
echo "Usage: forward_port <port_number>"
return 1
fi
local port=$1
/usr/bin/ssh -L ${port}:localhost:${port} nectar_co -N
}
function ssh-agent-fix() {
if [[ -n "$SSH_AUTH_SOCK" ]]; then
tmux set-environment -g SSH_AUTH_SOCK "$SSH_AUTH_SOCK" 2>/dev/null
export SSH_AUTH_SOCK=$(tmux show-environment -s SSH_AUTH_SOCK 2>/dev/null | sed 's/^SSH_AUTH_SOCK=//')
echo "SSH_AUTH_SOCK refreshed for tmux ✅"
else
echo "No SSH agent found ❌"
fi
}
# start jupyter lab
alias jupyter_lab_start="jupyter notebook --ip=0.0.0.0 --port=8888"
##########################
## github cli
##########################
export GIT_USER=`git config --list | grep user.name | cut -d = -f2`
# create gh aliases completion
if command -v gh > /dev/null; then
for al in $(gh alias list | grep -o -e '^[a-z].*:' | cut -d : -f1); do
alias gh_$al="gh $al"
done
fi
# load beets music tagging completions
#if command -v beet > /dev/null; then
# eval "$(beet completion)"
#fi
#
# forgit aliases https://github.com/wfxr/forgit written manually not to conflict
# with grc tool
alias ga=forgit::add
alias gcf=forgit::checkout::file
alias gbl=forgit::blame
alias gd=forgit::diff
alias glo=forgit::log
alias grh=forgit::reset::head
alias grco=forgit::revert::commit # grco not to conflict with grc
alias gcp=forgit::cherry::pick
alias gclean=forgit::clean
alias g='git'
#########################
## conda
#########################
# create autocompletion fzf for conda envs
function conda_activate () {
conda activate "$(conda info --envs | grep envs | fzf | awk '{print $1}')"
}
alias mamba_activate=conda_activate
function conda_destroy () {
local envs
envs=$(mamba info --envs | grep envs | fzf --multi --prompt="Select env(s) to destroy > " | awk '{print $1}')
[[ -z "$envs" ]] && return
while IFS= read -r env; do
mamba env remove -n "$env" --yes
done <<< "$envs"
}
alias conda_remove=conda_destroy
alias mamba_destroy=conda_destroy
# Interactive Poetry Activation (Zsh 2.0)
function poetry_activate() {
# 1. Try to find a local .venv first (fastest)
if [[ -f ".venv/bin/activate" ]]; then
source .venv/bin/activate
echo "Activated local .venv"
# 2. Fallback to asking poetry where the env is hidden
else
local env_path
env_path=$(poetry env info --path 2>/dev/null)
if [[ -n "$env_path" ]]; then
source "$env_path/bin/activate"
echo "Activated: $env_path"
else
echo "No poetry environment found. Run 'make dev' first."
fi
fi
}
alias pa=poetry_activate
#
# Interactive Poetry Environment Removal (Zsh Optimized)
function poetry_destroy() {
local envs
# Get all envs, allow multi-select with Tab
envs=$(poetry env list | fzf --multi --height 40% --reverse --prompt="Select Env(s) to Destroy (Tab to mark) > " | awk '{print $1}')
[[ -z "$envs" ]] && return
# Use Zsh parameter expansion (f) to iterate over lines properly
for env in ${(f)envs}; do
echo "Destroying: $env"
poetry env remove "$env"
done
}
alias pd=poetry_destroy
##########################
# Display
##########################
alias display_docked_work=". $HOME/.screenlayout/work_screen2_thunder.sh && mouse_setting.sh"
alias work_workspace='display_docked_work & tmux'
alias display_docked_home=". $HOME/.screenlayout/i3_work.sh && mouse_setting.sh"
alias home_workspace='display_docked_home & tmux'
alias display_undocked=". $HOME/.screenlayout/i3_laptop_single_screen.sh && mouse_setting.sh"
alias screen_layout='arandr'
alias brightness_up='sudo light -A 10'
alias brightness_down='sudo light -U 10'
alias brightness_chgrp_sys='/usr/bin/ansible-playbook -i hosts $ANSIBLE_PATH/local.yml -K -t i3'
##########################
# Various
##########################
alias rsrc='source ~/.bashrc'
alias clear_tmp="find /tmp -mtime +1 -and -not -exec fuser -s {} ';' -and -exec rm -Rf {} ';'"
alias fzfp="fzf -m --preview 'head -100 {}'"
alias sublime='subl'
alias grep='grep --color=auto'
alias trim="sed 's/^ *//;s/ *$//'"
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias copy='xclip -sel clip'
alias yy='copy'
alias automount='udiskie &'
alias update_linux='sudo mintupdate-launcher'
alias linux_version='neofetch'
alias musescore_dl='npx msdl'
alias path_env_path="echo $PATH | tr ':' '\n' | fzf"
[[ -s "$HOMEBREW_PREFIX/etc/grc.zsh" ]] && alias tail='grc tail'
if command -v cheat-linux-amd64 > /dev/null; then
alias cheat=cheat-linux-amd64
fi
alias irssi='screen irssi'
alias tmux_start="[[ ! $TERM =~ screen ]] && [ -z $TMUX ] && exec tmux -2 attach"
alias cleanup_cache="conda clean -a"
alias vita_dock="mplayer tv:// -tv driver=v4l2:device=/dev/video2:width=960:height=544"
function vita_update_all_games() {
local vita_path=/export/games/emulation/Playstation/PSVITA
cd $vita_path
for id in `fd -e zip -t f . --full-path $vita_path | grep -o -E "P[A-Z]{3}[0-9]{5}" | uniq | sort`; do
echo updating $(basename "$(fd -e zip -t f $id --full-path $vita_path --max-depth 1)")
$HOME/nopaystation_scripts/nps_update.sh $id
done
}
# file edit function in nvim/vim
function fe(){
nvim $(fd -LIH --type f | fzf -m --preview "([[ -f {} ]] && (bat --style=numbers --color=always {} || cat {}))")
}
function csv_viewer() {
local input_file=$1;
cat $input_file | column -t -s, | less -S
}
#https://github.com/junegunn/fzf/wiki/Examples
fman() {
man -k . | fzf -q "$1" --prompt='man> ' --reverse --preview $'echo {} | tr -d \'()\' | awk \'{printf "%s ", $2} {print $1}\' | xargs -r man | col -bx | bat -l man -p --color always' | tr -d '()' | awk '{printf "%s ", $2} {print $1}' | xargs -r man
}
# Get the colors in the opened man page itself
export MANPAGER="sh -c 'col -bx | bat -l man -p --paging always'"
##########################
# NETWORK
##########################
alias iftop_wlan='iftop -i wlan0'
alias lynx='lynx -cfg=~/.lynx.cfg'
alias elinks_google='elinks www.google.com.au'
alias mac_wlan_random='sudo ifconfig wlp1s0 down && sudo macchanger -r wlp1s0 && sudo ifconfig wlp1s0 up'
alias ports='netstat -tulanp' # open ports
alias ssh-add='ssh-add -t 10h'
alias wifi_restart='sudo systemctl restart wpa_supplicant.service'
alias wifi_connect_to='nmtui'
alias wifi_configure='nm-applet'
function host_via_which_route() {
local host=$1
# get the ip of that host (works with dns and /etc/hosts. In case we get
# multiple IP addresses, we just want one of them
host_ip=$(getent ahosts "$host" | awk '{print $1; exit}')
# only list the interface used to reach a specific host/IP. We only want the
# part between dev and src (use grep for that)
ip route get "$host_ip" | grep -Po '(?<=(dev )).*(?= src| proto)'
}
if command -v dig > /dev/null; then
alias myip="dig +short myip.opendns.com @resolver1.opendns.com"
alias mygeo="curl -w \"\\n\" http://api.hackertarget.com/geoip/\?q=\`myip\`"
else
alias myip="curl ifconfig.me"
fi
# vpn
#
fzf_ssh() {
local host
host=$(awk '/^Host / {for(i=2;i<=NF;i++) if ($i !~ /\*|^$/) print $i}' ~/.ssh/config | sort -u \
| fzf --height 40% --reverse --border --prompt='SSH> ' \
--preview 'awk "/^Host {}$/,/^Host /{if (!/^Host /) print}" ~/.ssh/config | head -20' \
--preview-window=down:5:hidden)
if [[ -n $host ]]; then
echo "Connecting to $host ..."
ssh "$host"
fi
}
alias s=fzf_ssh
#alias s='var=$(grep -e "^Host " ~/.ssh/config | sed "s#Host ##" | fzf) && ssh $var' # ssh with fzf to list known hosts from ssh/config
[ -f ~/.utas_vpnc.conf ] && alias vpn_utas_connect='sudo vpnc ~/.utas_vpnc.conf --local-port 0' && alias vpn_utas_disconnect='sudo vpnc-disconnect'
alias vpn_bfunk_start='sudo openvpn --cd $DOTFILES_PRIVATE_PATH/openvpn/ --writepid /run/openvpn/home.pid --config lbesnard.ovpn'
alias wg_bfunk_up='wg-quick up bfunk'
alias wg_bfunk_start='wg_bfunk_up'
alias wg_bfunk_down='wg-quick down bfunk'
alias wg_bfunk_stop='wg_bfunk_down'
alias wg_bfunk_restart='wg_bfunk_down && wg_bfunk_up'
alias wg_bfunk_route_force_start='sudo ip route del default; sudo ip route add default via 131.217.38.1 dev eth1; sudo ip route add $SERVER_LOCAL_IP via 11.13.13.4 dev bfunk; sudo ip route add 10.1.1.0/24 via 10.13.13.4 dev bfunk' # could be useful if wifi network has same network as vpn
##########################
# vim nvim alias
##########################
if command -v nvim > /dev/null; then
alias vim='nvim'
alias vi='nvim'
alias v='f -e nvim' # replace default fasd alias from zsh plugin
fi
alias vim_plugin_install="vim +'PlugInstall --sync' +'PlugUpdate' +qa"
if command -v bat > /dev/null; then alias cat="bat -p"; fi
##########################
# timezone
##########################
alias tz_paris='TZ="Europe/Paris" date'
alias tz_hobart='TZ="Australia/Hobart" date'
alias tz_utc='TZ="UTC" date'
##########################
# SYSTEM
##########################
if command -v htop > /dev/null; then alias top='htop'; fi
if command -v btop > /dev/null; then alias top='btop'; fi # replace htop with btop
if command -v dfc > /dev/null; then alias df='dfc'; fi
if command -v ncdu > /dev/null; then
alias gt5=ncdu
alias hdd_report=ncdu
fi
alias temperature='sensors;sudo hddtemp /dev/sda'
alias shutdown_now='sudo shutdown -h now'
alias latest_installed_pckg='cat /var/log/apt/history.log | grep "\ install\ "'
alias killall='killall -SIGUSR1'
alias lock_screen='gnome-screensaver-command --lock || xscreensaver-command -lock'
# should be replaced by kp but kp has some issues on the fzf preview
fkill() {
local pid
if [ "$UID" != "0" ]; then
pid=$(ps -f -u $UID | sed 1d | fzf -m | awk '{print $2}')
else
pid=$(ps -ef | sed 1d | fzf -m | awk '{print $2}')
fi
if [ "x$pid" != "x" ]
then
echo $pid | xargs kill -${1:-9}
fi
}
#########################
# DATABASE
#########################
if command -v pgcli > /dev/null; then
alias psql=pgcli
fi
# list hosts with fzf from pgpass file and connect to DB.
[ -f $HOME/.pgpass ] && export PGPASS_PATH=$HOME/.pgpass && alias psql-connect='var=$(cat $PGPASS_PATH | cut -d : -f1 | grep -v "^#" | fzf) && psql -d `cat $PGPASS_PATH | grep $var | cut -d':' -f3 | head -1` -h $var -U `cat $PGPASS_PATH | grep $var | cut -d':' -f4 | head -1`'
##########################
# file handling
##########################
remove_space_from_filename_recur() {
find . -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;
}
remove_file_extension() {
local file="$1"; shift
mv $file ${file%\.[^.]*}
}
bulk_rename() {
local find_pattern="$1"
local replace_pattern="$2"
if [[ -z "$find_pattern" || -z "$replace_pattern" ]]; then
echo "Usage: bulkrename <find_pattern> <replace_pattern>"
return 1
fi
fd "$find_pattern" -t f | while read -r file; do
new_name=$(echo "$file" | sed "s/$find_pattern/$replace_pattern/")
if [[ "$file" != "$new_name" ]]; then
echo "$file -> $new_name"
fi
done | fzf --multi --preview "echo {}" | awk '{print $1, $3}' | while read -r old new; do
mv "$old" "$new"
done
}
##########################
# NetCDF
##########################
list_error_netcdf() {
readlink -f * | cut -d '/' -f6 | sed -e 's/\.nc\..*/\.nc/g'
}
ncdumph() {
command ncdump -h "$@" | less;
}
ncbrowse() {
local uuid_regexp='[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
filepath=$( (fd -LHI nc.$uuid_regexp ; fd -LHI -e nc) | fzf --multi=1 --preview "([[ -f {} ]] && ncdump -h {})")
if [ ! -z "$filepath" ]
then
[ -f /mnt/ebs/pipeline/bin/activate ] && . /mnt/ebs/pipeline/bin/activate || conda activate ncvue
ncvue "$filepath"
[ -f /mnt/ebs/pipeline/bin/activate ] && deactivate || conda deactivate
fi
}
alias ncvue_plot=ncbrowse
_cc_activate_env() {
local conda_cc=1
[ -f /mnt/ebs/pyenv/versions/pipeline_prod_venv/bin/activate ] && . /mnt/ebs/pyenv/versions/pipeline_prod_venv/bin/activate && conda_cc=0
[ -f /mnt/ebs/pyenv/versions/pipeline_rc_venv/bin/activate ] && . /mnt/ebs/pyenv/versions/pipeline_rc_venv/bin/activate && conda_cc=0
if [ $conda_cc -eq "1" ]; then
conda activate python-aodndata-conda
fi
}
_cc_deactivate_env() {
local conda_cc=1
[ -f /mnt/ebs/pyenv/versions/pipeline_prod_venv/bin/activate ] && /mnt/ebs/pyenv/bin/pyenv deactivate && conda_cc=0
[ -f /mnt/ebs/pyenv/versions/pipeline_rc_venv/bin/activate ] && /mnt/ebs/pyenv/bin/pyenv deactivate && conda_cc=0
if [ $conda_cc -eq "1" ]; then
conda deactivate
fi
}
# compliance checker with fzf
_cc() {
local test=$1;shift
#[ -f /mnt/ebs/pipeline/bin/activate ] && . /mnt/ebs/pipeline/bin/activate || conda activate python-aodndata-conda
_cc_activate_env
local uuid_regexp='[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
filepath=$( (fd -LHI nc.$uuid_regexp ; fd -LHI -e nc) | fzf --multi=1 --preview "([[ -f {} ]] && ncdump -h {})")
if [ ! -z "$filepath" ]
then
#compliance-checker $test $(fd -LHI -e nc | fzf -m --preview "([[ -f {} ]] && ncdump -h {})")
compliance-checker $test $filepath
tmux split-window -h "ncdump -h \"$filepath\" | less"
#[ -f /mnt/ebs/pipeline/bin/activate ] && deactivate || conda deactivate
_cc_deactivate_env
fi
}
cc_cf() {
_cc -t=cf:latest
}
cc_cf_1.6() {
_cc -t=cf:1.6
}
# compliance checker running the imos1.4 check
cc_imos_1.3() {
_cc -t=imos:1.3
}
# compliance checker running the imos1.4 check
cc_imos_1.4() {
_cc -t=imos:1.4
}
# compliance checker running the ghrsst check
cc_ghrsst() {
_cc -t=ghrsst
}
###########################
# MUSIC
###########################
alias beet_genre_uniq_update="beet ls -f '\$genre' | sort -u > ~/.beets_genre"
alias split_flac_album='IFS=$(echo -en "\n\b"); for CUE in `find . -type f -name "*.cue"`; do FILE_TO_CONVERT=`basename ${CUE%.*}.flac` && shnsplit -f "$CUE" -t %n-%t -o flac "$FILE_TO_CONVERT" && rm -f "$FILE_TO_CONVERT";done'
alias split_ape_album='IFS=$(echo -en "\n\b"); for CUE in `find . -type f -name "*.cue"`; do FILE_TO_CONVERT=`basename ${CUE%.*}.ape` && shnsplit -f "$CUE" -t %n-%t -o flac "$FILE_TO_CONVERT" && rm -f "$FILE_TO_CONVERT";done'
alias split_wv_album='IFS=$(echo -en "\n\b"); for CUE in `find . -type f -name "*.cue"`; do FILE_TO_CONVERT=`basename ${CUE%.*}.wv` && shnsplit -f "$CUE" -t %n-%t -o flac "$FILE_TO_CONVERT" && rm -f "$FILE_TO_CONVERT";done'
alias split_flac_subfolders='IFS=$(echo -en "\n\b"); for f in `fd -a .cue`; do cd ```dirname $f```; split_flac_album ;done'
function spotify_pl_ls_missing () {
# download playlists
IFS=$(echo -en "\n\b");
local pl_path=/media/lbesnard/bfunk_10tb_3/music/beet_library/playlists_navidrome
local pl_val=`ls $pl_path | fzf --multi=1`
cat "$pl_path/$pl_val" | while read line; do
if [[ $line = \#* ]]
then
local albumartist=`echo "$line" | grep -o '#.*' | cut -d : -f2,4 | sort | uniq | sed "s/\"title\":/album:/g" | cut -d ',' -f1 | sed "s/\"//g" | sed "s/^ //g"`
local album=`echo "$line" | grep -o '#.*' | cut -d : -f2,4 | sort | uniq | sed "s/\"title\":/album:/g" | sed "s/, \"length\"//g" | cut -d ',' -f2 | sed "s/\"//g" | sed "s/^ //g" | sed "s/album: //g"`
local albumartist_replace=`echo "${albumartist}" | sed "s/ /+/g"`
local url="https://jackett.funkybrownfunk.duckdns.org/UI/Dashboard#search=$albumartist_replace&tracker=rutracker&category=3000&filter=all"
local str_line=`printf "albumartist: %s, album: %s, url: %s\n" "${albumartist}" "${album}" "$url"`
local str="$str\n$str_line"
fi
done
echo "$str" | sort | uniq
}
#alias music_player='mp3blaster'
alias music_player='flatpak run app.sublimemusic.SublimeMusic'
alias volume='pavucontrol'
###########################
# paragliding
###########################
alias flightrecorder='cd $HOME/paragliding ; sudo flightrecorder && chown $USER:$USER *.IGC; rsync -avc $HOME/paragliding/ $HOME/Nexctloud/paragliding_igc'
alias igc_viewer='gpligc'
alias riverHeight='python $GITHUB_DIR/River_Height_Tasmania/riverHeight.py && /usr/bin/elinks ~/Nexctloud/Public/RiverStatusTasmania.html'
alias gpsdump_flymaster='cd $HOME/Downloads; ./gpsdump -gy -ca0 -lflight'
alias paragliding_create_osm_map='$GITHUB_DIR/OSM_Tile_Download/osm_ogie3d.py'
##############################
# PYTHON
##############################
python_venv_init () {
local venv_name=$1; shift
mkdir "$venv_name" && cd "$venv_name"
python -m venv venv && source venv/bin/activate
xargs -a requirements.txt -n 1 pip install
}
alias pip_install_requirements='xargs -a requirements.txt -n 1 pip install'
kill_py () {
local python_script_name=$1; shift
kill -9 $(ps aux | grep "[p]ython.*${python_script_name}\.py" | awk '{print $2}')
}
##############################
# docker compose
##############################
#alias dcp='docker-compose -f /opt/docker-compose.yml '
#alias dcpull='docker-compose -f /opt/docker-compose.yml pull --parallel'
#alias dclogs='docker-compose -f /opt/docker-compose.yml logs -tf --tail="50" '
#alias dtail='docker logs -tf --tail="50" "$@"'
# replaced by fzf-docker
alias docker_logs_truncate='sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"' # can save 50Gb of logs easily!!
alias docker_logs_tail='docker ps --format "{{.Names}}" | fzf | xargs -I {} docker logs -f {}'
# from https://www.reddit.com/r/devops/comments/o5iwbk/useful_fzf_tricks/
alias docker_sh='docker exec -it $( docker ps --format "{{.Names}}" | fzf | awk '"'"'{print $1;}'"'"' ) sh'
alias docker_bash='docker exec -it $( docker ps --format "{{.Names}}" | fzf | awk '"'"'{print $1;}'"'"' ) bash'
alias docker_rm='docker rm $( docker ps --format "{{.Names}}" | fzf | awk '"'"'{print $1;}'"'"' )'
alias docker_rma='docker rm $( docker ps -a --format "{{.Names}}" | fzf | awk '"'"'{print $1;}'"'"' )'
alias docker_prune_images='docker image prune --all --force'
##############################
## BFUNK
##############################
alias mount_games='mount_point=games;mkdir -p $HOME/bfunk/$mount_point; sudo mount -t nfs $SERVER_LOCAL_IP:/export/$mount_point $HOME/bfunk/$mount_point/'
#alias start_vpn_torrent='sudo systemctl start vpn_access.service; sudo service transmission-daemon start; myip'
#alias stop_vpn_torrent='sudo service transmission-daemon stop; sudo systemctl stop vpn_access.service; myip'
#alias nginx_maintenance='sudo rm -f /etc/nginx/sites-enabled/* && sudo ln -s /etc/nginx/sites-available/omv_maintenance /etc/nginx/sites-enabled/omv_maintenance && sudo service nginx restart;'
#alias nginx_organizr='sudo rm -f /etc/nginx/sites-enabled/* && sudo ln -s /etc/nginx/sites-available/organizr /etc/nginx/sites-enabled/organizr && sudo service nginx restart;'
#alias filebot_movie_rename_dryrun='IFS=$(echo -en "\n\b"); for dir in `find -type d`; do filebot -rename $dir --db TheMovieDB --format "/export/torrent/{plex}" --action test; done'
#alias filebot_movie_rename_move='IFS=$(echo -en "\n\b"); for dir in `find -type d`; do filebot -rename $dir --db TheMovieDB --format "/export/torrent/{plex}" --action move; done'
#alias filebot_tvshows_rename_dryrun='filebot -rename -r -non-strict . --db TheTVDB --format "/export/torrent/{plex}" --action test'
#alias filebot_tvshows_rename_move='filebot -rename -r -non-strict . --db TheTVDB --format "/export/torrent/{plex}" --action move'
NEXCTLOUD_DATA_DIR=/export/nexctloud
# when files are copied manually to nextcloud folder
alias nextcloud_force_rescan='docker exec nextcloud sudo -u abc php /config/www/nextcloud/occ files:scan --all'
# ---------------------------------------------------------------------------
# funk_rsync / funk_rclone helpers
# ---------------------------------------------------------------------------
# Returns (and creates) the state directory for sync timestamps.
_funk_state_dir() {
local dir="$HOME/.local/share/funk_rsync"
mkdir -p "$dir"
echo "$dir"
}
# Returns the path to the per-task state file.
# Task names are sanitized (: / and spaces → _) to form a safe filename.
_funk_state_file() {
local task_name="$1"
local safe_name="${task_name//[:\/]/_}"
safe_name="${safe_name// /_}"
echo "$(_funk_state_dir)/$safe_name"
}
# Cache of mount points loaded from /proc/mounts (lazy, one read per session).
_funk_mounts_cache=""
# Returns true if the destination path's underlying mount point is available.
# Reads /proc/mounts once and caches the result for the session.
# Handles both Ubuntu (/media/USER/DRIVE) and NixOS (/run/media/USER/DRIVE) layouts.
_funk_dest_is_available() {
local dest="${1%/}" # strip trailing slash so ${path:h} doesn't skip the mount point
# Skip placeholder destinations
[[ -z "$dest" || "$dest" == "TO_BE_FILLED_MANUALLY" ]] && return 1
# Populate cache once (colon-delimited list of mount points)
if [[ -z "$_funk_mounts_cache" ]]; then
_funk_mounts_cache=$(awk '{print $2}' /proc/mounts 2>/dev/null | tr '\n' ':')
fi
# Paths to walk up: the destination itself, plus /run<dest> for NixOS
# (/media/USER/DRIVE configs also mount at /run/media/USER/DRIVE on NixOS)
local -a candidates=("$dest")
[[ "$dest" == /media/* ]] && candidates+=("/run$dest")
local candidate path stop_at
for candidate in "${candidates[@]}"; do
# For /run/media/... paths stop walking before /run/media itself
# (which is a tmpfs, not a drive mount)
stop_at="/"
[[ "$candidate" == /run/media/* ]] && stop_at="/run/media"
path="$candidate"
while [[ "$path" != "$stop_at" && "$path" != "/" ]]; do
if [[ ":${_funk_mounts_cache}:" == *":${path}:"* ]]; then
return 0
fi
path="${path:h}"
done
done
# No mount found — local paths are always ok, media paths are not
case "$dest" in
/media/*|/mnt/*|/run/media/*) return 1 ;;
*) return 0 ;;
esac
}
# Returns a formatted last-sync string for fzf display.
_funk_last_sync_info() {
local task_name="$1"
local state_file
state_file=$(_funk_state_file "$task_name")
if [[ -f "$state_file" ]]; then
local ts
ts=$(cat "$state_file")
# Format to YYYY-MM-DD HH:MM (trim seconds and timezone)
echo "last: ${ts:0:16}"
else
echo "never synced"
fi
}
# Records a successful sync timestamp for a task.
_funk_record_sync() {
local task_name="$1"
local state_file
state_file=$(_funk_state_file "$task_name")
date -Iseconds > "$state_file"
}
# ---------------------------------------------------------------------------
# delete function without. can be added manually in optional
# arguments. This removes the risks of deleting files if I/O error
function funk_rsync() {
local server_ip="$1"; shift
local folder_to_bckp="$1"; shift
local src="/data/$folder_to_bckp"
local dest="$1/$folder_to_bckp";shift
# The remaining arguments in "$@" are the extra options passed from funk_rsync_config
mkdir -p $dest
# Pass the remaining arguments "$@" directly to rsync
[ -d $dest ] && rsync -auvh -P --delete-after --delete-excluded -e "ssh -i ~/.ssh/id_rsa -p 9000 -l root" $server_ip:$src/ $dest/ \
--stats --progress --exclude ".*lrprev" --exclude jellyfin/ \
--exclude "uploaded_piwigo" --exclude "piwigo" --exclude='*.tmp' \
--exclude="*.jpg_original*" \
--exclude="docker_photoprism" \
--exclude="photoprism" \
--exclude="komga/logs/.*" \
--exclude="komga/lucene/.*" \
--exclude="komga/artemis/.*" \
--exclude='.bazarr.log.*' \
--exclude='lidarr/logs/*' \
--exclude='radarr/logs/*' \
--exclude='radarr_fr/logs/.*' \
--exclude='MediaCover/*' \
--exclude='Navidrome/cache/.*' \
--exclude="*.log" --exclude="*.log\..*\.gz" \
--exclude="*.page" --exclude="*.amq" \
--exclude=.deleted "$@" || echo "$dest does not exist" # Use "$@" directly
}
_ensure_ssh_key_loaded () {
export SSH_AUTH_SOCK="$HOME/.ssh/ssh-agent.sock"
ssh-add -l &> /dev/null
local ssh_exit_code=$?
if [ $ssh_exit_code -eq 2 ] || [[ ! -S "$SSH_AUTH_SOCK" ]]; then
echo "SSH agent unreachable or socket dead. Restarting..."
rm -f "$SSH_AUTH_SOCK"
eval "$(ssh-agent -s -a "$SSH_AUTH_SOCK")" > /dev/null
fi
if ! ssh-add -l &> /dev/null; then
echo "No SSH keys loaded. Running ssh-add..."
ssh-add -t 10h
fi
}
function funk_rclone() {
_ensure_ssh_key_loaded
local server_ip="$1"; shift
local folder_to_bckp="$1"; shift
local src="/data/$folder_to_bckp"
local dest_root="$1"; shift
local dest="$dest_root/$folder_to_bckp"
mkdir -p "$dest"
local rclone_conf="$HOME/.config/rclone/rclone.conf"
local rclone_src
if [[ -f "$rclone_conf" ]]; then
# Use the remote defined in rclone.conf and override the host
# This assumes you named the remote [funk_sftp] in the file
rclone_src="funk_sftp,host=$server_ip:$src"
else
# Fallback to on-the-fly backend if no config exists
rclone_src=":sftp,host=$server_ip,port=9000,user=root,use_agent_auth=true,skip_hostkey_check=true:$src"
fi
if [ -d "$dest" ]; then
rclone sync "$rclone_src" "$dest" \
--progress \
--use-mmap \
--sftp-ciphers aes128-gcm@openssh.com \
--transfers 16 \
--checkers 32 \
--buffer-size 64M \
--delete-after \
--exclude ".*lrprev" \
--exclude "jellyfin/**" \
--exclude "uploaded_piwigo/**" \
--exclude "piwigo/**" \
--exclude "*.tmp" \
--exclude "*.jpg_original*" \
--exclude "docker_photoprism/**" \
--exclude "photoprism/**" \
--exclude "komga/logs/**" \
--exclude "komga/lucene/**" \
--exclude "komga/artemis/**" \
--exclude ".bazarr.log.*" \
--exclude "lidarr/logs/**" \
--exclude "radarr/logs/**" \
--exclude "radarr_fr/logs/**" \
--exclude "MediaCover/**" \
--exclude "Navidrome/cache/**" \
--exclude "*.log" \
--exclude "*.log.*.gz" \
--exclude "*.page" \
--exclude "*.amq" \
--exclude ".deleted" \
"$@"
else
echo "Error: $dest could not be created."
fi
}
function funk_rsync_config() {
# Check if jq is installed
if ! command -v jq &>/dev/null; then
echo "Error: 'jq' is not installed. Please install it and try again."
return 1
fi
# Check if fzf is installed
if ! command -v fzf &>/dev/null; then
echo "Error: 'fzf' is not installed. Please install it and try again."
return 1
fi
local config_file="$HOME/.funk_rsync_config.json"
# Check if the configuration file exists
if [[ ! -f "$config_file" ]]; then
echo "Error: Configuration file '$config_file' not found."
return 1
fi
# Build the fzf list: only tasks whose destination is mounted, with last-sync info
local fzf_lines=() dest sync_info
while IFS= read -r task_name; do
dest=$(jq -r --arg t "$task_name" '.tasks[] | select(.name == $t) | .destination' "$config_file")
_funk_dest_is_available "$dest" || continue
sync_info=$(_funk_last_sync_info "$task_name")
fzf_lines+=("${task_name} │ ${sync_info}")
done < <(jq -r '.tasks[].name' "$config_file")
if [[ ${#fzf_lines[@]} -eq 0 ]]; then
echo "No tasks with available destinations found."
return 1
fi
# Show picker and extract task name (before the │ delimiter)
local selected_line
selected_line=$(printf '%s\n' "${fzf_lines[@]}" | fzf --prompt="Select a task: " --height=15 --border --ansi)
[[ -z "$selected_line" ]] && { echo "No task selected. Exiting."; return 1; }
local selected_task
selected_task=$(echo "$selected_line" | awk -F' │ ' '{print $1}')
# Extract the selected task's details from the JSON
local server_ip folder_to_bckp dest
server_ip=$(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task) | .server)' "$config_file")
folder_to_bckp=$(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task) | .source)' "$config_file")
dest=$(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task) | .destination)' "$config_file")
local extra_rsync_options=()
while IFS= read -r line; do
extra_rsync_options+=("$line")
done < <(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task)) | .rsync_options[]' "$config_file")
# Call funk_rsync; record timestamp on success
funk_rsync "$server_ip" "$folder_to_bckp" "$dest" "${extra_rsync_options[@]}" "$@"
local exit_code=$?
[[ $exit_code -eq 0 ]] && _funk_record_sync "$selected_task"
return $exit_code
}
function funk_rclone_config() {
_ensure_ssh_key_loaded
if ! command -v jq &>/dev/null || ! command -v fzf &>/dev/null; then
echo "Error: 'jq' and 'fzf' are required."
return 1
fi
local config_file="$HOME/.funk_rsync_config.json"
if [[ ! -f "$config_file" ]]; then
echo "Error: Configuration file '$config_file' not found."
return 1
fi
# Build the fzf list: only tasks whose destination is mounted, with last-sync info
local fzf_lines=() dest sync_info
while IFS= read -r task_name; do
dest=$(jq -r --arg t "$task_name" '.tasks[] | select(.name == $t) | .destination' "$config_file")
_funk_dest_is_available "$dest" || continue
sync_info=$(_funk_last_sync_info "$task_name")
fzf_lines+=("${task_name} │ ${sync_info}")
done < <(jq -r '.tasks[].name' "$config_file")
if [[ ${#fzf_lines[@]} -eq 0 ]]; then
echo "No tasks with available destinations found."
return 1
fi
# Show picker and extract task name (before the │ delimiter)
local selected_line
selected_line=$(printf '%s\n' "${fzf_lines[@]}" | fzf --prompt="Select a task: " --height=15 --border)
[[ -z "$selected_line" ]] && return 1
local selected_task
selected_task=$(echo "$selected_line" | awk -F' │ ' '{print $1}')
local server_ip folder_to_bckp dest
server_ip=$(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task) | .server)' "$config_file")
folder_to_bckp=$(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task) | .source)' "$config_file")
dest=$(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task) | .destination)' "$config_file")
local extra_options=()
while IFS= read -r line; do
extra_options+=("$line")
done < <(jq -r --arg task "$selected_task" 'first(.tasks[] | select(.name == $task)) | .rclone_options[]' "$config_file")
print -P "%F{green}❯ $selected_task%f"
funk_rclone "$server_ip" "$folder_to_bckp" "$dest" "${extra_options[@]}" "$@"
local exit_code=$?
[[ $exit_code -eq 0 ]] && _funk_record_sync "$selected_task"
return $exit_code
}
function funk_rsync_cron() {
local out_machine="$1"
local config_file="$HOME/.funk_rsync_config.json"
if [[ -z "$out_machine" ]]; then
echo "Usage: funk_rsync_cron <out_machine_name>"
return 1
fi
if ! command -v jq &>/dev/null; then
echo "Error: 'jq' is not installed."
return 1
fi
if [[ ! -f "$config_file" ]]; then
echo "Error: Configuration file '$config_file' not found."
return 1