Skip to content

Instantly share code, notes, and snippets.

@klaushardt
Last active July 17, 2024 06:02
Show Gist options
  • Save klaushardt/9a5f6b0b078d28a23fd968f7549f6bba to your computer and use it in GitHub Desktop.
Save klaushardt/9a5f6b0b078d28a23fd968f7549f6bba to your computer and use it in GitHub Desktop.
Collected usefull Snippets

Unsorted usefull stuff collected from the interwebs

tmux detach other client

tmux a -d

use it in .ssh/config

Host servername
        HostName 192.168.1.123
        Port 22
        User deploy
        IdentityFile ~/.ssh/servername-deploy
        RequestTTY yes
        RemoteCommand tmux a -d

https://blog.jbowen.dev/tips/ssh-tmux/

alternative in .zshrc

 # launch tmux at shell login https://wiki.archlinux.org/index.php/Tmux
 [[ $- != *i* ]] && return
 if [[ -z "$TMUX" ]] ;then
     ID="`tmux ls | grep -m1 windows | cut -d: -f1`" # get the id of a deattached session
     if [[ -z "$ID" ]] ;then # if not available create a new one
         tmux new-session
     else
         tmux attach-session -t "$ID" # if available attach to it
     fi
 fi

SSL_ERROR_RX_RECORD_TOO_LONG

a2enmod ssl headers proxy proxy_ajp
a2ensite default-ssl

https://stackoverflow.com/questions/119336/ssl-error-rx-record-too-long-and-apache-ssl

How to Remove PEM Password

You can use the openssl rsa command to remove the passphrase. As arguments, we pass in the SSL .key and get a .key file as output.

openssl rsa -in futurestudio_with_pass.key -out futurestudio.key

The documentation for openssl rsa explicitly recommends to not choose the same input and output filenames. This command will ask you one last time for your PEM passphrase. Type the password, confirm with enter key and you’re done. Finally! Nginx won’t ask for the PEM passphrase anymore and you’re free to reload and restart nginx as much as you want.

https://futurestud.io/tutorials/how-to-remove-pem-password-from-ssl-certificate

Get Public IP

# IPv4 or if present IPv6 autoselect
curl icanhazip.com
# force IPv4
curl -4 icanhazip.com
curl ipv4.icanhazip.com
# force IPv6
curl -6 icanhazip.com
curl ipv6.icanhazip.com

DNS lookup

# use google dns
nslookup example.com 8.8.8.8

Disc Space Insurance File

fallocate -l 8G /tmp/DELETE_IF_OUT_OF_SPACE.img

Find with fzf

find * -type f | fzf

Devices and mount points

lsblk

VIm paste mode

`:set paste` then `:set nopaste` and `:wq`

rsync from source to target and delete on source

rsync -avz --remove-source-files -e ssh user@192.168.1.123:/home/user/source /home/user/target

ripgrep

rg search *
# just read the docs, better than grep in everything
# * default recursive
# * replace mode with -r

https://github.com/BurntSushi/ripgrep/blob/master/GUIDE.md

docker

docker images -f dangling=true
docker rmi $(docker images -q)
docker volume ls -qf dangling=true | xargs -r docker volume rm
docker stats $(docker ps --format={{.Names}})

Aliases

cat << EOF >> ~/.zshrc
#Gives you what is using the most space. Both directories and files. Varies on current directory
alias most='du -hsx * | sort -rh | head -10'
#I use this one when I need to find the files that has been added/modified most recently:
alias lt=ls -alrt

alias path='echo -e ${PATH//:/\\n}'
alias now='date +"%T"'
alias nowtime=now
alias nowdate='date +"%d-%m-%Y"'
alias ports='netstat -tulanp'

# https://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html#comment-21989
# do not delete / or prompt if deleting more than 3 files at a time #
#alias rm='rm -I --preserve-root'
#A co-worker had such an alias. Imagine the disaster when, visiting a customer site,
#he did "rm *" in the customers work directory and all he got was the prompt for
#the next command after rm had done what it was told to do.
#It you want a safety net, do "alias del=rm -I -preserve_root'
alias del="rm -I -preserve_root"

# Parenting changing perms on / #
 alias chown='chown --preserve-root'
 alias chmod='chmod --preserve-root'
 alias chgrp='chgrp --preserve-root'
 
 ## pass options to free ##
alias meminfo='free -m -l -t -h'

## get top process eating memory
alias psmem='ps auxf | sort -nr -k 4'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'

## get top process eating cpu ##
alias pscpu='ps auxf | sort -nr -k 3'
alias pscpu10='ps auxf | sort -nr -k 3 | head -10'

## this one saved by butt so many times ##
alias wget='wget -c'

## set some other defaults ##
alias df='df -H'
alias du='du -ch'

#progress bar on file copy. Useful evenlocal.
alias cpProgress="rsync --progress -ravz"
EOF

cryptmount

sudo cat << EOF > /opt/cryptmount.sh
#!/bin/bash
sudo cryptsetup open --type luks /dev/disk/by-id/wwn-0x5000cca099ce10f8-part1 btrfs_parity1 #sdb1
sudo cryptsetup open --type luks /dev/disk/by-id/wwn-0x5000cca3b7cd2e7b-part1 btrfs_pool1 #sda1
sudo cryptsetup open --type luks /dev/disk/by-id/wwn-0x5000cca099cc0efb-part1 btrfs_pool2 #sdd1
sudo mount /dev/mapper/btrfs_parity1 /media/parity1
sudo mount /dev/mapper/btrfs_pool1 /media/disk1
sudo mount /dev/mapper/btrfs_pool2 /media/disk2
sudo mergerfs -o use_ino,direct_io,defaults,allow_other,minfreespace=50G,fsname=mergerfs /media/disk1:/media/disk2 /media/btrfs
EOF
alias cryptmount='sudo /opt/cryptmount.sh'

dpkg-backup

cat << EOF > dpkg-backup.sh
#!/bin/sh
dpkg --get-selections > ~/.config/dpkg-backup/Package.list
cp -R /etc/apt/sources.list* ~/.config/dpkg-backup/
apt-key exportall > ~/.config/dpkg-backup/Repo.keys
EOF

cat << EOF > dpkg-restore.sh
#!/bin/sh
apt-key add ~/.config/dpkg-backup/Repo.keys
cp -R ~/.config/dpkg-backup/sources.list* /etc/apt/
apt-get update
apt-get install dselect
dselect update
dpkg --set-selections < ~/.config/dpkg-backup/Package.list
apt-get dselect-upgrade -y
EOF

https://askubuntu.com/a/99151 Check if this still works. Some comments here suggest a new solution.

check if root in bash script

(( `id -u` )) && echo "Must be root" && exit 1

https://stackoverflow.com/a/974939

cd to previous directory

cd -
# Example
/usr/local/bin> cd /i/am/a/banana
/i/am/a/banana> cd -
/usr/local/bin>

https://stackoverflow.com/a/966078

rename temp files

# Renaming/moving files with suffixes quickly:
cp /home/foo/realllylongname.cpp{,-old}

# This expands to:
cp /home/foo/realllylongname.cpp /home/foo/realllylongname.cpp-old

# Just to point out that to do the reverse (going from .cpp-old to .cpp) you'd do
cp /home/foo/realllylongname.cpp{-old,}

# This expands to:
cp /home/foo/realllylongname.cpp-old /home/foo/realllylongname.cpp

https://stackoverflow.com/a/68600

repeat last arguments

Esc. Inserts the last arguments from your last bash command. It comes in handy more than you think.

cp file /to/some/long/path <ENTER> # Hit Enter
cd <ESC><.> # write cd, then space, then hit Esc, then hit .
# expands to cd /to/some/long/path

https://stackoverflow.com/a/68419

diff command over ssh

As another example, let's say I want to check if two servers have the same list of RPMs installed. Rather than sshing to each server, writing each list of RPMs to separate files, and doing a diff on those files, I can just do the diff from my workstation:

$ diff <(ssh server1 'rpm -qa | sort') <(ssh server2 'rpm -qa | sort')
241c240
< kernel-2.6.18-92.1.6.el5
---
> kernel-2.6.18-92.el5
317d315
< libsmi-0.4.5-2.el5
727,728d724
< wireshark-0.99.7-1.el5
< wireshark-gnome-0.99.7-1.el5
$

https://stackoverflow.com/a/164795

sed remove lines in place

macOS: sed -i '' '/^remove/d' file
linux: sed -i '/^remove/d' file

https://stackoverflow.com/questions/12696125/sed-edit-file-in-place/12696224#12696224

Extract all *.rar Files in all subdirs into their own folder

find ./ -type f -name "*.rar" -execdir unrar x -o- -p- {} \;
# && delete *.rar files after success
find ./ -type f -name "*.rar" -execdir sh -c 'unrar x -o- -p- "{}" && rm "{}"' \;

pipefail

#!/bin/bash
set -eu -o pipefail
# TODO: rest off the script goes here
#!/bin/bash
set -euxo pipefail
if [ -z "${New_Var:-}" ]; then
 echo "New_Var has no value assigned to it."
fi
# TODO: rest off the script goes here

https://www.howtogeek.com/782514/how-to-use-set-and-pipefail-in-bash-scripts-on-linux/

Midnight Commander

Selecting files

Insert (Ctrl + t alternatively) – select files (for example, for copying, moving or deleting).
+ – select files based on a pattern.
\ –unselect files based on a pattern.
* – reverse selection. If nothing was selected, all files will get selected.

Accessing the shell

There’s a shell awaiting your command at the bottom of the screen – just start typing (when no other command dialog is open, of course).
Since Tab is bound to switching panels (or moving the focus in dialogs), you have to use Esc Tab to use autocompletion. Hit it twice to get all the possible completions (just like in a shell). This works in dialogs too.
If you want inspect the output of the command, do some input or just prefer a bigger console, no need to quit mc. Just hit Ctrl + o – the effect will be similar to putting mc in the background but with a nice perk. Your current working directory from mc will be passed on to the shell… and vice versa! Hit Ctrl + o again to return to mc.
Ctrl + Enter or Alt + Enter – copy the currently selected file’s name to the shell.
Ctrl + Shift + Enter – same as above, but the full path is copied.

Internal viewer (F3) and editor (F4)

The internal viewer has many built in modes for “previewing” the content of the file. Try “viewing” a binary, an archive, a DOC document or an image. In some cases, external programs are needed in order for this “previewing” to work.
If you want to preview the “raw” contents of the file, hit Shift + F3.
While the internal viewer and editor are powerful, sometimes you want to use your preferred software (coughvimcough). You can do so by setting the PAGER (for viewer) and EDITOR (for editor) variables (for example, in your ~/.bashrc file). Then toggle the Options -> Configuration -> Use interal edit/view option (access the top menu by pressing F9).

Panels

Alt + , – switch mc’s layout from left-right to top-bottom. Mind = blown. Useful for operating on files with long names.
Alt + t – switch the panel’s listing mode in a loop: default, brief, long, user-defined. “long” is especially useful, because it maximises one panel so that it takes full width of the window and longer filenames fit on screen.
Alt + i – synchronize the active panel with the other panel. That is, show the current directory in the other panel.
Ctrl + u – swap panels.
Alt + o – if the currently selected file is a directory, load that directory on the other panel and move the selection to the next file. If the currently selected file is not a directory, load the parent directory on the other panel and moves the selection to the next file. This is useful for quick checking the contents of a list of directories.
Ctrl + PgUp (or just left arrow, if you’ve enabled Lynx-like motion, see later) – move to the parent directory.
Alt + Shift + h – show the directory history. Might be easier to navigate than going back one entry at a time.
Alt + y – move to the previous directory in history.
Alt + u – move to the next directory in history.

Searching files

Alt + ? – shows the full Find dialog.
Alt + s or Ctrl + s – quick search mode. Start typing and the selection will move to the first matching file. Press the shortcut again to jump to another match. Use wildcards (*, ?) for easier matching.

Common actions

Ctrl + Space – calculate the size of the selected directories. Press this shortcut when the selection is on .. to calculate the size of all the directories in the current directory.
Ctrl + x s (that is press Ctrl + x, let it go and then press s) – create a symbolic link (change s to l for a hardlink). I find it very useful and intuitive – the link will, of course, be created in the other panel. You can change it’s destination and name, like with any other file operation.
Ctrl + x c – open the chmod dialog.
Ctrl + x o – open the chown dialog.

Useful options

Configuration
    Verbose operation and Compute totals – so that operations like copy/move have a more detailed progress dialogs.
Layout
    Equal split – uncheck to define your own ratio for panels. Maybe you prefer one panel bigger than the other? Useful especially if you keep one of the panels in tree mode (or maybe info/quick view, too).
    Uncheck Hintbar visible – one more line available, one less line of noise.
Panel options
    Show backup files and Show hidden files – I keep both enabled, as I often work with configuration files, etc.
    Lynx-like motion – mentioned above, makes left arrow go to parent directory, while the right arrow enters the directory under selection. Faster than Home, Enter, Home, Enter, etc. This options is quite smart, that is if the shell command line is not empty, the arrows work as usual and allow moving the cursor in the command line.
    File highlight -> File types is useful, as it uses a different color for example for executable files. Permissions, for me, is not that useful, but I can definitely see it’s use, for example, for sysadmins.
Appearance
    Only one option here, Skins. You can check out different skins shipped with mc – just select one from the list. I prefer gotar, because it plays well with my solarized terminal colors.
    Useful tip – set up a different skin when logged in as the root user. It’ll be easier to differentiate between root’s and normal user’s session, when you’re swapping between them (as is often the case).

Bonus assignments

Define your own listing mode (Right/Left -> Listing mode... -> User defined). Hit F1 to see available columns and options.
Play around in tree mode: Right/Left -> Tree or Command -> Directory tree.
Compare directories (Ctrl + x d)
Fill up the directory hotlist (Ctrl + \)

https://klimer.eu/2015/05/01/use-midnight-commander-like-a-pro/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment