-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathzshrc
More file actions
1743 lines (1480 loc) · 57.1 KB
/
Copy pathzshrc
File metadata and controls
1743 lines (1480 loc) · 57.1 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
# -- Powerlevel10k Instant Prompt (MUST be at the very top) --
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
# -- PATH Configuration --
# This ensures all your locally installed programs are found first.
export PATH="$HOME/.local/bin:$HOME/bin:$PATH"
# (Keeping your custom .capt paths from your original file)
#export PATH="/home/$USER/.capt:/home/$USER/.capt/root/usr/local/sbin:/home/$USER/.capt/root/usr/local/bin:/home/$USER/.capt/root/usr/sbin:/home/$USER/.capt/root/usr/bin:/home/$USER/.capt/root/sbin:/home/$USER/.capt/root/bin:/home/$USER/.capt/root/usr/games:/home/$USER/.capt/root/usr/local/games:/home/$USER/.capt/snap/bin:$PATH"
#export LD_LIBRARY_PATH="/home/$USER/.capt/root/lib/x86_64-linux-gnu:/home/$USER/.capt/root/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH"
# -- Oh My Zsh Configuration --
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="powerlevel10k/powerlevel10k"
plugins=(git sudo history docker zsh-autosuggestions zsh-syntax-highlighting colored-man-pages)
source $ZSH/oh-my-zsh.sh
# -- Shell Settings --
HISTFILE=~/.zsh_history
HISTSIZE=10000
SAVEHIST=10000
export EDITOR='vim'
export LANG=en_US.UTF-8
# -- Your Custom Aliases & Functions --
alias zshconfig="vim ~/.zshrc"
alias ohmyzsh="vim ~/.oh-my-zsh"
alias gs="git status"
alias gd="git diff"
alias ..="cd .."
alias ...="cd ../.."
alias c="clear"
alias h="history"
alias valgrind_all='valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes'
alias sanitize_all='clang -g -O1 -fsanitize=address -fno-omit-frame-pointer -o sancheck.out'
#alias readline_path="echo '-I$HOME/readline/include -L$HOME/readline/lib -lreadline -lncurses'"
alias cclean='bash ~/Cleaner_42.sh'
#alias mstest="bash ~/42_minishell_tester/tester.sh"
alias fkill="ps -ef | fzf | awk '{print \$2}' | xargs kill -9"
alias r="ranger"
alias ocr="~/.local/bin/gnome-ocr-area.sh"
#-----------------STARTTTTT
#-----------------STARTTTTT
alias ci='zi'
autoload -Uz edit-command-line
zle -N edit-command-line
bindkey '^X^E' edit-command-line
# ls in each time call cd
#
autoload -Uz add-zsh-hook
function list_on_cd() { ls }
add-zsh-hook chpwd list_on_cd
# ctl + X +c copy command buffer into system clipboard
#
function copy-buffer() {
echo -n "$BUFFER" | wl-copy # Use wl-copy for Linux/Wayland else pbcopy
zle -M "Buffer copied"
}
zle -N copy-buffer
bindkey '^Xc' copy-buffer
alias dps='docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"'
# Fuzzy Search through containers to stop on# Stop containers with Fuzzy Search
#
#
# Exec into container - Compatible with older fzf
dex() {
local cid
# tail -n +2 removes the header line
cid=$(docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}" | tail -n +2 | fzf | awk '{print $1}')
if [ -n "$cid" ]; then
# Attempts bash, falls back to sh if bash isn't installed in the image
docker exec -it "$cid" /bin/bash 2>/dev/null || docker exec -it "$cid" /bin/sh
fi
}
# Stop containers - Logic for ancient fzf versions
ds-stop() {
local cid
# Use tail to skip the first line (header) manually
cid=$(docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}" | tail -n +2 | fzf | awk '{print $1}')
[ -n "$cid" ] && docker stop $cid
}
# Remove images - Logic for ancient fzf versions
di-rm() {
local img
img=$(docker images --format "table {{.ID}}\t{{.Repository}}\t{{.Tag}}" | tail -n +2 | fzf | awk '{print $1}')
[ -n "$img" ] && docker rmi $img
}
alias lzd='lazydocker'
#
#!/bin/zsh
# ═══════════════════════════════════════════════════════════════════════════
# 🚀 SMART PUSH FUNCTIONS - The Perfect File Transfer Automation
# ═══════════════════════════════════════════════════════════════════════════
# Add this to your ~/.zshrc or source it: source ~/smart_push_functions.zsh
#
# Usage:
# push <file> <server> [remote_path] [key]
# pushlive <server> [file]
#
# Examples:
# push deployment.yaml thejoceph-k8s.duckdns.org
# push nginx.conf 54.123.45.67 /etc/nginx/
# pushlive thejoceph-k8s.duckdns.org deployment.yaml
# ═══════════════════════════════════════════════════════════════════════════
# ─────────────────────────────────────────────────────────────────────────
# Function 1: push - The Intelligent File Uploader
# ─────────────────────────────────────────────────────────────────────────
push() {
local FILE=$1
local SERVER=$2
local REMOTE_PATH=${3:-"~/mylaptop"} # Default to ~/mylaptop folder
local SSH_KEY=$4
local REMOTE_USER=""
local RESOLVED_IP=""
# ─── Validation ───
if [[ -z "$FILE" || -z "$SERVER" ]]; then
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Usage: push <file> <server> [remote_path] [key]"
echo ""
echo "Examples:"
echo " push deploy.yaml thejoceph-k8s.duckdns.org"
echo " push script.sh 192.168.1.10 /opt/scripts/"
echo " push config.conf myserver ~/configs/ custom.pem"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
return 1
fi
if [[ ! -f "$FILE" ]]; then
echo "❌ Error: File '$FILE' not found"
return 1
fi
# ─── Auto-detect SSH Key ───
if [[ -z "$SSH_KEY" ]]; then
# Try default first
if [[ -f ~/Downloads/k8s_course.pem ]]; then
SSH_KEY=~/Downloads/k8s_course.pem
echo "🔑 Using default key: k8s_course.pem"
elif [[ -f ~/.ssh/k8s_course.pem ]]; then
SSH_KEY=~/.ssh/k8s_course.pem
echo "🔑 Using key from ~/.ssh/k8s_course.pem"
else
# Show selection menu
echo "🔍 No default key found. Available keys in ~/.ssh/:"
local keys=(~/.ssh/*.pem(N) ~/.ssh/id_*(N))
if [[ ${#keys[@]} -eq 0 ]]; then
echo "❌ No SSH keys found in ~/.ssh/"
echo "💡 Trying without key (password auth)..."
SSH_KEY=""
else
local i=1
for key in "${keys[@]}"; do
echo " [$i] $(basename $key)"
((i++))
done
echo -n "Select key number (or press Enter to try without key): "
read selection
if [[ -n "$selection" && "$selection" =~ ^[0-9]+$ ]]; then
SSH_KEY="${keys[$selection]}"
echo "🔑 Selected: $(basename $SSH_KEY)"
else
SSH_KEY=""
echo "⚠️ Proceeding without SSH key"
fi
fi
fi
else
# Expand tilde if present
SSH_KEY="${SSH_KEY/#\~/$HOME}"
if [[ ! -f "$SSH_KEY" ]]; then
echo "❌ Error: Key file '$SSH_KEY' not found"
return 1
fi
fi
# ─── Auto-detect Remote User ───
# Check if server contains user@ prefix
# ─── Auto-detect Remote User ───
# Check if server contains user@ prefix
if [[ "$SERVER" =~ ^(.+)@(.+)$ ]]; then
REMOTE_USER="${match[1]}"
SERVER="${match[2]}"
echo "👤 Using specified user: $REMOTE_USER"
else
# Auto-detect based on server characteristics
if [[ "$SERVER" =~ (amazon|aws|ec2|duckdns) ]]; then
REMOTE_USER="ubuntu"
echo "👤 Auto-detected AWS/Ubuntu server → user: ubuntu"
elif [[ "$SERVER" =~ (al2023|amazonlinux) ]]; then
REMOTE_USER="ec2-user"
echo "👤 Auto-detected Amazon Linux → user: ec2-user"
else
# Default to ubuntu for unknown servers
REMOTE_USER="ubuntu"
echo "👤 Using default user: ubuntu"
fi
fi
# ─── DNS Resolution & Connectivity Check ───
# ─── DNS Resolution & Connectivity Check ───
echo "🌐 Resolving server address: $SERVER"
# Check if it's already an IP
if [[ "$SERVER" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
RESOLVED_IP="$SERVER"
echo "✓ Direct IP detected: $RESOLVED_IP"
else
# Try to resolve DNS (compatible with rg alias)
RESOLVED_IP=$(dig +short "$SERVER" | command grep -E '^[0-9.]+$' | head -n1)
if [[ -z "$RESOLVED_IP" ]]; then
# Fallback to host command
RESOLVED_IP=$(host "$SERVER" 2>/dev/null | command grep "has address" | awk '{print $4}' | head -n1)
fi
if [[ -n "$RESOLVED_IP" ]]; then
echo "✓ Resolved $SERVER → $RESOLVED_IP"
else
echo "⚠️ Could not resolve DNS. Trying direct connection..."
RESOLVED_IP="$SERVER"
fi
fi
# Quick connectivity check (with timeout)
echo "📡 Testing connectivity..."
if nc -z -w 3 "$RESOLVED_IP" 22 2>/dev/null; then
echo "✓ SSH port (22) is reachable"
else
echo "⚠️ Warning: Cannot reach SSH port. Server might be down or firewalled."
echo -n "Continue anyway? [y/N]: "
read confirm
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
echo "❌ Upload cancelled"
return 1
fi
fi
# ─── Build SCP Command ───
local SCP_CMD="scp"
if [[ -n "$SSH_KEY" ]]; then
SCP_CMD="$SCP_CMD -i \"$SSH_KEY\""
fi
# Add options for better UX
SCP_CMD="$SCP_CMD -o ConnectTimeout=10 -o StrictHostKeyChecking=no"
# Ensure remote path ends with / to indicate it's a directory
local FINAL_REMOTE_PATH="$REMOTE_PATH"
if [[ ! "$FINAL_REMOTE_PATH" =~ /$ ]]; then
FINAL_REMOTE_PATH="${FINAL_REMOTE_PATH}/"
fi
local DESTINATION="${REMOTE_USER}@${SERVER}:${FINAL_REMOTE_PATH}"
# ─── Execute Transfer ───
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🚀 Uploading: $FILE"
echo "📍 To: ${DESTINATION}$(basename $FILE)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
eval "$SCP_CMD \"$FILE\" \"$DESTINATION\""
if [ $? -eq 0 ]; then
echo ""
echo "✅ SUCCESS: File uploaded to ${REMOTE_USER}@${SERVER}:${FINAL_REMOTE_PATH}$(basename $FILE)"
echo "💡 To apply: ssh ${REMOTE_USER}@${SERVER} \"kubectl apply -f ${FINAL_REMOTE_PATH}$(basename $FILE)\""
else
echo ""
echo "❌ FAILED: Upload error"
echo "🔧 Troubleshooting:"
echo " • Verify server is running"
echo " • Check SSH key permissions: chmod 400 $SSH_KEY"
echo " • Test manual connection: ssh ${REMOTE_USER}@${SERVER}"
return 1
fi
}
# ─────────────────────────────────────────────────────────────────────────
# Function 2: pushlive - Live Neovim Editing Over SCP
# ─────────────────────────────────────────────────────────────────────────
pushlive() {
local SERVER=$1
local FILE=${2:-""}
local REMOTE_USER="ubuntu"
local SSH_KEY=""
if [[ -z "$SERVER" ]]; then
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Usage: pushlive <server> [file]"
echo ""
echo "Examples:"
echo " pushlive thejoceph-k8s.duckdns.org deployment.yaml"
echo " pushlive 192.168.1.10"
echo ""
echo "Opens Neovim in live-sync mode. Every :w saves directly to remote."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
return 1
fi
# ─── Auto-detect SSH Key ───
if [[ -f ~/Downloads/k8s_course.pem ]]; then
SSH_KEY=~/Downloads/k8s_course.pem
elif [[ -f ~/.ssh/k8s_course.pem ]]; then
SSH_KEY=~/.ssh/k8s_course.pem
fi
# ─── Build Neovim SCP URL ───
local SCP_URL="scp://${REMOTE_USER}@${SERVER}//home/${REMOTE_USER}/mylaptop/"
if [[ -n "$FILE" ]]; then
SCP_URL="${SCP_URL}${FILE}"
fi
echo "🔗 Opening live session to: $SERVER"
echo "📂 Remote path: /home/${REMOTE_USER}/mylaptop/"
echo "💡 Press :w in Neovim to save directly to server"
echo ""
# ─── Set SSH identity for Neovim ───
if [[ -n "$SSH_KEY" ]]; then
export NVIM_SCP_KEY="$SSH_KEY"
# Neovim will use this via .ssh/config or we can pass via env
fi
# ─── Launch Neovim ───
if command -v nvim &> /dev/null; then
nvim "$SCP_URL"
else
echo "❌ Neovim not found. Install with: sudo apt install neovim"
return 1
fi
}
# ─────────────────────────────────────────────────────────────────────────
# Bonus: Quick SSH Connection Helper
# ─────────────────────────────────────────────────────────────────────────
kssh() {
local SERVER=$1
local SSH_KEY=~/Downloads/k8s_course.pem
if [[ -z "$SERVER" ]]; then
echo "Usage: kssh <server>"
return 1
fi
if [[ ! -f "$SSH_KEY" ]]; then
SSH_KEY=~/.ssh/k8s_course.pem
fi
echo "🔐 Connecting to $SERVER..."
ssh -i "$SSH_KEY" ubuntu@"$SERVER"
}
# ─────────────────────────────────────────────────────────────────────────
# Auto-completion Setup (Optional but Professional)
# ─────────────────────────────────────────────────────────────────────────
# Uncomment to enable tab-completion for server names
# compdef '_files' push
# compdef '_hosts' pushlive
#
# echo "✅ Smart Push Functions Loaded"
# echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# echo "Available commands:"
# echo " push - Upload files intelligently"
# echo " pushlive - Live Neovim editing"
# echo " kssh - Quick SSH connection"
# echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
#
alias mydns='echo thejoceph-k8s.duckdns.org'
#--------------------------------- ENDDDDD
alias v="vim"
alias md='glow -p'
dark_mode() {
gsettings set org.gnome.desktop.interface gtk-theme 'Adwaita-dark'
}
# ===========================
alias cdwn='curl -L -C - -O'
alias cdown='curl -L -C - -o'
alias cks='curl -L -k'
alias chead='curl -I -L'
alias cverb='curl -v -L'
function cgetjson() {
[ -z "$1" ] && { echo "Usage: cgetjson <URL>"; return 1; }
curl -s -L -H "Accept: application/json" "$1" | jq .
}
function cpost() {
[ -z "$2" ] && { echo "Usage: cpost <URL> <DATA_OR_FILE>"; return 1; }
[[ "$2" == @* ]] && curl -X POST -s -L -H "Content-Type: application/json" -d "$2" "$1" | jq . || curl -X POST -s -L -H "Content-Type: application/json" -d "$2" "$1" | jq .
}
function cput() {
[ -z "$2" ] && { echo "Usage: cput <URL> <DATA_OR_FILE>"; return 1; }
[[ "$2" == @* ]] && curl -X PUT -s -L -H "Content-Type: application/json" -d "$2" "$1" | jq . || curl -X PUT -s -L -H "Content-Type: application/json" -d "$2" "$1" | jq .
}
function cdel() {
[ -z "$1" ] && { echo "Usage: cdel <URL>"; return 1; }
curl -X DELETE -s -L "$1" | jq .
}
function cresolve() {
[ -z "$3" ] && { echo "Usage: cresolve <DOMAIN> <IP:PORT> <URL>"; return 1; }
curl -v -L --resolve "$1:${2##*:}:$2" "$3"
}
function chost() {
[ -z "$2" ] && { echo "Usage: chost <HOST_HEADER> <URL>"; return 1; }
curl -v -L -H "Host: $1" "$2"
}
function cauth() {
[ -z "$3" ] && { echo "Usage: cauth <USER> <PASS> <URL>"; return 1; }
curl -v -L -u "$1:$2" "$3"
}
# ===========================
alias jqp='jq .'
alias jqk='jq keys'
alias jql='jq length'
function jval() {
[ -z "$1" ] && { echo "Usage: ... | jval <KEY>"; return 1; }
jq -r ".$1"
}
function jfield() {
[ -z "$1" ] && { echo "Usage: ... | jfield <KEY>"; return 1; }
jq -r '.[].'$1
}
function jfields() {
[ $# -eq 0 ] && { echo "Usage: ... | jfields <KEY1> <KEY2> ..."; return 1; }
local query_parts=""
for key in "$@"; do query_parts+=".$key, "; done
jq -r '.[] | ['"${query_parts%, }"'] | @tsv' | column -t
}
function jfind() {
if [ -z "$2" ]; then
echo "Usage: ... | jfind <KEY> <VALUE>"
echo " ... | jfind <KEY> <VALUE> --contains (for partial match)"
return 1
fi
local key="$1"
local value="$2"
local mode="${3:-exact}"
if [[ "$mode" == "--contains" || "$3" == "-c" ]]; then
# Partial match (contains)
jq --arg k "$key" --arg v "$value" '
if type == "array" then
map(select(.[$k] | tostring | contains($v)))
else
select(.[$k] | tostring | contains($v))
end
'
else
# Exact match
jq --arg k "$key" --arg v "$value" '
if type == "array" then
map(select(.[$k] == $v))
else
select(.[$k] == $v)
end
'
fi
}
alias ...='cd ../../..'
alias gp='git push'
alias gl='git pull'
alias gc='git commit'
alias ~='cd ~'
# ===========================
function extract() {
if [ -z "$1" ]; then
echo "Usage: extract <archive_file>"
return 1
fi
if [ ! -f "$1" ]; then
echo "Error: '$1' is not a valid file"
return 1
fi
case "$1" in
*.tar.bz2) tar xjf "$1" ;;
*.tar.gz) tar xzf "$1" ;;
*.tar.xz) tar xJf "$1" ;;
*.bz2) bunzip2 "$1" ;;
*.rar) unrar x "$1" ;;
*.gz) gunzip "$1" ;;
*.tar) tar xf "$1" ;;
*.tbz2) tar xjf "$1" ;;
*.tgz) tar xzf "$1" ;;
*.zip) unzip "$1" ;;
*.Z) uncompress "$1" ;;
*.7z) 7z x "$1" ;;
*) echo "Error: '$1' cannot be extracted via extract()" ;;
esac
}
# Usage: extract archive.tar.gz
function gitignore() {
if [ -z "$1" ]; then
echo "Usage: gitignore <language/framework>"
echo "Examples: gitignore python, gitignore node, gitignore c"
return 1
fi
local lang=$(echo "$1" | tr '[:upper:]' '[:lower:]')
curl -sL "https://www.toptal.com/developers/gitignore/api/$lang" -o .gitignore
if [ $? -eq 0 ]; then
echo "✅ .gitignore created for: $1"
echo "📄 Preview:"
head -20 .gitignore
else
echo "❌ Failed to generate .gitignore for: $1"
fi
}
# Usage: gitignore python
# Usage: gitignore c,vim,linux
function backup() {
if [ -z "$1" ]; then
echo "Usage: backup <file_or_directory>"
return 1
fi
if [ ! -e "$1" ]; then
echo "Error: '$1' does not exist"
return 1
fi
local timestamp=$(date +"%Y%m%d_%H%M%S")
local backup_name="${1}_backup_${timestamp}"
if [ -d "$1" ]; then
cp -r "$1" "$backup_name"
echo "✅ Directory backed up: $backup_name"
else
cp "$1" "$backup_name"
echo "✅ File backed up: $backup_name"
fi
# Show backup size
du -sh "$backup_name" 2>/dev/null | awk '{print "📦 Size: " $1}'
}
# Usage: backup important_file.c
# Usage: backup my_project/
# Creates: important_file.c_backup_20250103_143022
function serve() {
local port="${1:-8000}"
echo "🌐 Starting HTTP server on port $port"
echo "📂 Serving: $(pwd)"
echo "🔗 Access at: http://localhost:$port"
echo "⏹️ Press Ctrl+C to stop"
echo ""
# Try Python 3 first, then Python 2, then PHP
if command -v python3 &>/dev/null; then
python3 -m http.server "$port"
elif command -v python &>/dev/null; then
python -m SimpleHTTPServer "$port"
elif command -v php &>/dev/null; then
php -S "localhost:$port"
else
echo "❌ Error: No server found (install python3)"
return 1
fi
}
# Usage: serve # Starts on port 8000
# Usage: serve 3000 # Starts on port 3000
function pfind() {
local pid
# Show all processes with nice formatting, let user pick
pid=$(ps aux | sed 1d | fzf --multi --header="[SELECT PROCESS]" | awk '{print $2}')
if [ -z "$pid" ]; then
echo "No process selected"
return 0
fi
echo "Selected PID(s): $pid"
echo ""
echo "Actions:"
echo " 1) Show details"
echo " 2) Kill (SIGTERM)"
echo " 3) Force kill (SIGKILL)"
echo " 4) Cancel"
echo ""
read -p "Choose action [1-4]: " action
case $action in
1)
echo "$pid" | xargs -I {} ps -p {} -f
;;
2)
echo "$pid" | xargs kill
echo "✅ Sent SIGTERM to process(es)"
;;
3)
echo "$pid" | xargs kill -9
echo "✅ Force killed process(es)"
;;
*)
echo "Cancelled"
;;
esac
}
# Usage: pfind
# Then type to search: "node", "python", "vim", etc.
# Cat all files based on extenstion or none for all in dir and subdir
cat_exts() {
# If no extensions are provided, assume all files are desired.
if [ $# -eq 0 ]; then
find . -type f -print0 | xargs -0 cat
return 0
fi
local find_args=()
local first_ext=1
for ext in "$@"; do
# Add a leading dot if it's missing (e.g., 'py' becomes '.py')
if [[ "${ext:0:1}" != "." ]]; then
ext=".${ext}"
fi
if [[ "$first_ext" -eq 1 ]]; then
find_args+=( -name "*${ext}" )
first_ext=0
else
find_args+=( -o -name "*${ext}" )
fi
done
# find . -type f ( -name "*.py" -o -name "*.md" ) ...
find . -type f \( "${find_args[@]}" \) -print0 | xargs -0 cat
}
# ============================================================
# SUPER USEFUL QUICK ALIASES
# ============================================================
# File operations
alias cpv='rsync -ah --info=progress2'
alias ports='netstat -tulanp'
alias myip='curl -s ifconfig.me'
# Development
alias npmls='npm list --depth=0'
alias pipls='pip list --format=columns'
alias venv='python3 -m venv venv && source venv/bin/activate'
# Docker
alias dps='docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"'
alias dstop='docker stop $(docker ps -q)'
alias dclean='docker system prune -af'
# ===========================
# -- Task Management --
alias tda='todo.sh add' # Quickly add a new task
alias tdl='todo.sh list | sort' # List all pending tasks
alias tdd='todo.sh done' # Mark a task as done by its number
alias tdr='todo.sh del' # Remove a task by its number
alias tdp='todo.sh pri' # Set priority for a task
# better to add fonts of the "Fira Fonts"
alias ls='eza --icons --git'
alias ll='eza -l --long --header --icons --git'
alias la='eza -a --icons --git'
alias tree='eza --tree'
# Show large directories (>10MB) including hidden ones, sorted by size from biggger to smalr
alias bigdirs='du -sh ~/.[^.]* ~/* 2>/dev/null | awk '\''$1 ~ /^[1-9][0-9]+M$|^[0-9]+G$|^[0-9]+T$/'\'' | sort -hr'
# Show large files (>10MB) with human readable sizes
alias bigfiles='find ~ -type f -size +10M -printf "%s %p\n" 2>/dev/null | awk '\''{size=$1/(1024*1024); printf "%.1fM %s\n", size, substr($0, index($0,$2))}'\'' | sort -nr'
# Show both large directories & files (comprehensive view)
alias bigstuff='echo "=== LARGE DIRECTORIES ===" && bigdirs && echo -e "\n=== LARGE FILES ===" && bigfiles'
# Show disk usage of current directory contents (including hidden alsoo)
alias duh='du -sh .[^.]* * 2>/dev/null | sort -hr'
# Show top 10 largest items in current directory
alias du10='du -sh .[^.]* * 2>/dev/null | sort -hr | head -10'
alias cat='bat -p --paging=never'
alias grep='rg'
alias cd='z'
eval "$(zoxide init zsh)"
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
# -- Find & Edit file with fzf and vim
vf() {
local file
file=$(fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}')
if [[ -n $file ]]; then
vim "$file"
fi
}
cf() {
local file
file=$(fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}')
if [[ -n $file ]]; then
cat "$file"
fi
}
# smarter grep function
fgr() {
local selected
selected=$(rg --line-number --color=always '' | fzf --ansi)
if [[ -z "$selected" ]]; then
return 0
fi
local file
local line
file=$(echo "$selected" | cut -d ':' -f 1)
line=$(echo "$selected" | cut -d ':' -f 2)
if [[ -n "$file" && -n "$line" ]]; then
vim "+$line" "$file"
fi
}
# --- Git Workflow Enhancement ---
gia() {
local files_to_add
files_to_add=$(git -c color.status=always status --short | \
fzf -m --ansi --preview 'bat --color=always {+2}')
if [[ -n "$files_to_add" ]]; then
echo "$files_to_add" | awk '{print $2}' | xargs git add
git status
fi
}
# 2. Interactive Git Checkout (`gco`)
unalias gco
gco() {
local branches branch
branches=$(git branch --all | grep -v HEAD | sed 's/remotes\/origin\///g' | sed 's/^\s*//g' | sort | uniq)
branch=$(echo "$branches" | fzf-tmux -d 20 --prompt="Checkout branch: ")
if [[ -n "$branch" ]]; then
git checkout "$branch"
fi
}
# 3. Interactive Git Log (`glo`)
unalias glo
glo() {
git log --graph --pretty=format:'%C(yellow)%h%Creset -%C(bold blue)%d%Creset %s %Cgreen(%cr) %C(bold magenta)<%an>%Creset' --abbrev-commit | fzf --ansi --no-sort --reverse --preview 'git show --color=always {1}'
}
# --- Smarter File & Directory Management ---
# 4. Make Directory and cd Into It (`mkcd`)
mkcd() {
mkdir -p "$1" && cd "$1"
}
# 5. Find and Edit Recent Files (`fer`)
fer() {
local file
file=$(find . -type f -mtime -1 | fzf --preview 'bat --color=always {}')
if [[ -n "$file" ]]; then
vim "$file"
fi
}
# Usage: <command> | cpy OR cpy <filename>
cpy() {
# Use an array for the command and its arguments
local copy_cmd
# Detect the correct copy command for the OS
if command -v xclip >/dev/null 2>&1; then
# Store command and arguments separately in an array
copy_cmd=('xclip' '-selection' 'clipboard')
elif command -v pbcopy >/dev/null 2>&1; then
copy_cmd=('pbcopy') # For macOS
else
echo "❌ Error: No clipboard tool (xclip, pbcopy) found."
return 1
fi
# Check if data is being piped in or given as a file argument
if [ -t 0 ]; then
# No piped data, treat arguments as filenames
if [ $# -eq 0 ]; then
echo "📋 Usage: <command> | cpy OR cpy <filename>"
return 1
fi
# Execute the command correctly from the array
cat "$@" | "${copy_cmd[@]}"
echo "✅ Copied content of file: $@"
else
# Data is being piped in from another command
# Execute the command correctly from the array
"${copy_cmd[@]}"
echo "✅ Copied piped output to clipboard."
fi
}
port() {
lsof -i :"$1"
}
weather() {
curl wttr.in/Khouribga
}
del() {
# The -0 flags tell fd, fzf, and xargs to use a special character (null)
fd --type f --hidden --exclude .git -0 | \
fzf -m --read0 --preview 'bat --color=always {}' | \
xargs -0 -r rm -v
}
# 5. Find all TODOs and FIXMEs ('todo')
alias todo='rg --color=always -i "(todo|fixme)"'
alias update="sudo apt update -y && sudo apt upgrade -y && sudo apt autoremove -y && sudo snap refresh && flatpak update -y && sudo aptitude update && sudo aptitude safe-upgrade -y "
# ============================================================
# INTERACTIVE TERMINAL CHEATSHEET & HELP SYSTEM
# ============================================================
# Usage: cheat [category] or just 'cheat' for interactive menu
cheat() {
local category="${1:-menu}"
# Color definitions
local RED='\033[0;31m'
local GREEN='\033[0;32m'
local YELLOW='\033[1;33m'
local BLUE='\033[0;34m'
local MAGENTA='\033[0;35m'
local CYAN='\033[0;36m'
local WHITE='\033[1;37m'
local BOLD='\033[1m'
local NC='\033[0m' # No Color
show_header() {
clear
echo -e "${CYAN}${BOLD}"
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ ║"
echo "║ 🚀 TERMINAL PRODUCTIVITY CHEATSHEET 🚀 ║"
echo "║ ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo -e "${NC}\n"
}
show_menu() {
show_header
echo -e "${WHITE}${BOLD}Select a category:${NC}\n"
echo -e "${GREEN} 1)${NC} CURL & API Testing"
echo -e "${GREEN} 2)${NC} JQ JSON Processing"
echo -e "${GREEN} 3)${NC} Essential Functions"
echo -e "${GREEN} 4)${NC} TMUX Commands"
echo -e "${GREEN} 5)${NC} VIM Commands"
echo -e "${GREEN} 6)${NC} Git Workflow"
echo -e "${GREEN} 7)${NC} File Operations"
echo -e "${GREEN} 8)${NC} System Monitoring"
echo -e "${GREEN} 9)${NC} Docker Utilities"
echo -e "${GREEN} 10)${NC} All Commands (Searchable)"
echo -e "${GREEN} 0)${NC} Exit"
echo ""
echo -n "Enter choice [0-10]: "
read choice
case $choice in
1) show_curl ;;
2) show_jq ;;
3) show_essential ;;
4) show_tmux ;;
5) show_vim ;;
6) show_git ;;
7) show_files ;;
8) show_system ;;
9) show_docker ;;
10) search_all ;;
0) return ;;
*) echo "Invalid choice"; sleep 1; show_menu ;;
esac
}
show_curl() {
show_header
echo -e "${YELLOW}${BOLD}═══ CURL & API TESTING ═══${NC}\n"
echo -e "${CYAN}Basic Aliases:${NC}"
echo -e " ${GREEN}c${NC} curl Quick curl shorthand"
echo -e " ${GREEN}cdwn${NC} curl -L -C - -O Resumable download"
echo -e " ${GREEN}chead${NC} curl -I -L Fetch headers only"
echo -e " ${GREEN}cverb${NC} curl -v -L Verbose debugging"
echo -e "\n${CYAN}API Testing Functions:${NC}"
echo -e " ${GREEN}cgetjson <url>${NC} GET JSON with pretty print"
echo -e " ${GREEN}cpost <url> <data>${NC} POST JSON data"
echo -e " ${GREEN}cput <url> <data>${NC} PUT JSON data"
echo -e " ${GREEN}cdel <url>${NC} DELETE request"
echo -e "\n${CYAN}Advanced Network:${NC}"
echo -e " ${GREEN}cresolve <domain> <ip:port> <url>${NC} Test DNS override"
echo -e " ${GREEN}chost <header> <url>${NC} Override Host header"
echo -e " ${GREEN}cauth <user> <pass> <url>${NC} Test basic auth"
echo -e "\n${MAGENTA}Examples:${NC}"
echo -e " ${BLUE}cgetjson https://api.github.com/users/yomazini${NC}"
echo -e " ${BLUE}cpost https://api.test.com/users '{\"name\":\"John\"}'${NC}"
echo -e " ${BLUE}chead https://example.com${NC}"
pause_menu
}
show_jq() {
show_header
echo -e "${YELLOW}${BOLD}═══ JQ JSON PROCESSING ═══${NC}\n"
echo -e "${CYAN}Basic Aliases:${NC}"
echo -e " ${GREEN}jqp${NC} jq . Pretty print JSON"
echo -e " ${GREEN}jqk${NC} jq keys List all keys"
echo -e " ${GREEN}jql${NC} jq length Count items"