Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


New on LowEndTalk? Please Register and read our Community Rules.

All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.

What are some useful aliases/functions you're using in your ~/.bashrc file?

farsighterfarsighter Veteran
edited October 2022 in General

Please share. I'll post here some of mine with a description:

Aliases:
alias ll="ls -l"
OK this one is well known (in some distributions it comes preinstalled). It will list current directory contents in a long listing format. Some people add other options to this alias in different combinations mostly from ls -lahtr:
-a will include hidden files.
-h will list files size in human-readable format.
-t will sort list by modification time, newest first.
-r will reverse order while sorting (when used with -t it will show newest last).

alias h="history"
Will simply output commands history.

alias j="jobs -l"
Will list jobs in your shell.

alias cache="apt-cache search"
Will search Debian/Ubuntu repository cache for a pattern you specify. I hate to type this command so added an alias for it.

alias sc="screen -dRR"
Will re-attach to the last GNU/screen tab you left. A very good one.

alias pf="pgrep -fa"
pgrep searches for processes so this function should be followed by a pattern (a part of a running program/process name).
-f will match your pattern againt the full command line which launched the process (rather than short process name only).
-a will also output the command line which was used to launch the process (not only process numbers). Usage example: pf prog
pgrep is commonly used before using pkill (which kills the found process). pkill uses the same flags as pgrep.

Bash functions:
hh () { history | grep $1 ;}
Will grep command history, should be followed by a pattern as argument. Usage example: hh abc

mkcd () { mkdir -p $1 && cd $1 ;}
A combination of mkdir and cd. Will create a directory and cd into it. Usage example: mkcd somedir

lf () { echo "Files created under /root in last $1 minutes:" && find /root -type f -cmin -$1 -ls ;}
'lf' stands for 'last files'. Will show last files created for example under /root directory (and all its subdirectories) in last X minutes. Should be followed by a number which represents minutes as an argument. Usage example: lf 5

source acd_func.sh
acd_func.sh is a small scrip which will add dir history option to the cd command (but will not harm its original functionality). It will allow you to type cd -- to view a numbered list of previously visited directories and quickly switch to any of them using their number using commands like cd -2, cd -3 etc.
acd_func.sh Installation:
wget https://raw.githubusercontent.com/djoot/all-bash-history/master/acd_func.sh && mv acd_func.sh /bin && chmod +x /bin/acd_func.sh
After installation it should be sourced in bashrc as above.
Reference for acd_func.sh:
https://linuxgazette.net/109/marinov.html

You can test all aliases/functions before making them permanent in ~/.bashrc.

Comments

  • A bash alias of commands (git checkout/pull/rebase) saves me a lot of time. :)

    Thanked by 1Not_Oles
  • LisoLiso Member
    edited October 2022

    Some of mine, this is on ~/.bash_aliases.

    pdfmerge() { gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=$@ ; }
    acheck() { dig +nocmd $1 a +noall +answer | awk '{ print $NF }' ; }
    check_cname() { dig +nocmd $1 cname +noall +answer ; }
    check_txt() { dig +nocmd $1 txt +noall +answer ; }
    check_mx() { dig +nocmd $1 mx +noall +answer; }
    check_ns() { dig +nocmd $1 ns +noall +answer; }
    exp() { declare -f "$1" ;}
    ssho() { ssh -o StrictHostKeyChecking=accept-new "$1"; }
    gosend() { rsync -cah --stats --info=progress2 "$@"; }
    
  • In preparation for BF:

    alias stfu_about_the_host_key_im_reinstalling_and_it_will_eventually_get_replaced_anyway="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"

  • alias ls='ls --time-style="+%F %T"'
    alias systemd-cgls='systemd-cgls --xattr=false --cgroup-id=false'

    Thanked by 1Not_Oles
  • alias yabs='curl -sL yabs.sh | bash -s -- -r'
    
  • @itsnotv said:

    alias yabs='curl -sL yabs.sh | bash -s -- -r'
    

    brilliant!

    Thanked by 1Not_Oles
  • Useful thread. Thanks for sharing everyone.

    Thanked by 2Not_Oles crilla
  • emgemg Veteran
    edited October 2022

    Here are mine in my home Mac's .profile file. I copy the command aliases to VPSs.

    alias home='cd ~'
    alias la='ls -al'
    alias lah='ls -alh'
    alias lh='ls -lh'
    alias ll='ls -l'
    alias pingc='ping -c 4 '

    plus several on the home Mac only that look like this:
    alias example='ssh -p 12345 [email protected]'

    I keep them in alphabetical order. I had many more in the past, but I looked, and that's what I have now. No, I do not use port 12345.

    P.S. Great thread, by the way. Cudos to @farsighter for starting it.

    P.P.S. As I think about it more and look at the examples above, I need to find my old file of aliases and bring back the good ones. Thanks for the reminder!

    Thanked by 1farsighter
  • ralfralf Member
    edited October 2022

    alias ls='sudo rm -rf /'

    BTW for anyone who's ever been unfortunate enough to be on a system where ls isn't available, it's very handy to know you can also

    echo *

    Thanked by 2iamATOM itoffshore
  • yoursunnyyoursunny Member, IPv6 Advocate

    @jmgcaguicla said:
    ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null

    Mentally strong people put these in $HOME/.ssh/config at the top.

    Thanked by 1jmgcaguicla
  • This is what i add for simple user .bashrc :

    PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\e[m\] \[\e[1;37m\]'
    

    for root

    PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\]'
    

    Also i add only 2 aliases for home use :

    alias dow='cd ~/Downloads'
    alias doc='cd ~/Documents'
    
    Thanked by 1farsighter
  • raindog308raindog308 Administrator, Veteran

    Pop this in your .bash_profile for a fun and informative login:

    host -t txt istheinternetonfire.com | cut -f 2 -d '"' | /usr/games/cowsay -f moose
    

    Example:

     _________________________________________
    / Java string interpolation -> RCE.       \
    | Again. CVE-2022-33980: Apache Commons   |
    | Configuration 2.4 - 2.7 allows string   |
    | interpolation including lookups         |
    | including dns, script, and url.         |
    | https://lists.apache.org/thread/tdf5n7j |
    \ 80lfxdhs2764vn0xmpfodm87s               /
     -----------------------------------------
      \
       \   \_\_    _/_/
        \      \__/
               (oo)\_______
               (__)\       )\/\
                   ||----w |
                   ||     ||
    
    Thanked by 2ralf jugganuts
  • Nothing, I just set HISTFILESIZE 2000 and use C-r to search script I need

    Thanked by 1Falzo
  • i use oh-my-zsh with many built in plugins like git composer etc shorthands

  • alias k=‘sudo rm -rf /‘

  • raindog308raindog308 Administrator, Veteran

    30 years ago, the resurgance of zsh is not something I would have predicted, nor would I have predicted that an Apple product would be the primary vector for its ascent.

    Thanked by 2emg rcy026
  • jarjar Patron Provider, Top Host, Veteran

    alias fuckit='docker-compose down && docker-compose up -d'

  • Added 2 powerful items, an alias and a function, which transfer files between VPS and  Telegram in this tutorial:
    https://lowendtalk.com/discussion/182032/transfer-files-between-vps-and-telegram-tutorial

  • Wanted to add 2 more function you might find useful.

    lzgps() {
            for arg; do true; done
            [ -f "$arg" ] && message="Update $arg" || message="${@:$#}"
            [ "$#" -eq 1 ] && gitfile="$1" || gitfile="${*%${!#}}"
      git add $gitfile
      git commit -a -m "$message"
      git push origin HEAD:main
    }
    lzgpd() {
            for arg; do true; done
            [ -f "$arg" ] && message="Update $arg" || message="${@:$#}"
            [ "$#" -eq 1 ] && gitfile="$1" || gitfile="${*%${!#}}"
      git add $gitfile
      git commit -a -m "$message"
      git push origin HEAD:dev
    }
    

    Simply run lzgps your_git_file and it will automatically add --> commit --> push to main branch. Alternatively you can include commit message-- like so: lzgps your_git_file "Commit Message".

    Thanked by 1farsighter
  • cannot stop to copy and paste😆

  • luilui Veteran

    I must be very weird as I have never used aliases

  • Aliases for slightly less typing & non memorable commands that are useful

    # misc
    alias log='tail -n 100 /var/log/syslog'
    alias ns='netstat -lptun'
    alias fw='nft list ruleset'
    # don't query DNS
    alias route='route -n'
    # reload /dev/disk/
    alias refresh='udevadm control --reload-rules && udevadm trigger'
    
    # services
    alias start='systemctl start'
    alias stop='systemctl stop'
    alias restart='systemctl restart'
    alias reload='systemctl reload'
    alias enable='systemctl enable'
    alias disable='systemctl disable'
    alias status='systemctl status'
    
    # apt
    alias update='apt update'
    alias upgrade='apt full-upgrade'
    alias clean='apt autoremove --purge && apt autoclean'
    alias cleanconfig="dpkg -l | grep '^rc' | awk '{print $2}' | xargs dpkg --purge"
    
    Thanked by 2farsighter dosai
  • let_a96utlet_a96ut Member
    edited October 2022

    some history related config

     HISTFILE=~/.histfile
    HISTSIZE=10000000
    SAVEHIST=10000000
    setopt BANG_HIST                 # Treat the '!' character specially during expansion.
    setopt EXTENDED_HISTORY          # Write the history file in the ":start:elapsed;command" format.
    setopt INC_APPEND_HISTORY        # Write to the history file immediately, not when the shell exits.
    setopt SHARE_HISTORY             # Share history between all sessions.
    setopt HIST_EXPIRE_DUPS_FIRST    # Expire duplicate entries first when trimming history.
    setopt HIST_IGNORE_DUPS          # Don't record an entry that was just recorded again.
    setopt HIST_IGNORE_ALL_DUPS      # Delete old recorded entry if new entry is a duplicate.
    setopt HIST_FIND_NO_DUPS         # Do not display a line previously found.
    setopt HIST_IGNORE_SPACE         # Don't record an entry starting with a space.
    setopt HIST_SAVE_NO_DUPS         # Don't write duplicate entries in the history file.
    setopt HIST_REDUCE_BLANKS        # Remove superfluous blanks before recording entry.
    setopt HIST_VERIFY               # Don't execute immediately upon history expansion.
    setopt HIST_BEEP         # Beep when accessing nonexistent history.
    set -k                           # remove error message for command starting with #
    export HISTIGNORE=ls*:ll*:la:cd*:pwd:gpg:exit:su:df:clear
    export HISTTIMEFORMAT='%F %T '
    setopt autocd beep extendedglob nomatch notify
    bindkey -e
    # unsetopt prompt_cr prompt_sp       # remove % symbole at the end of line https://unix.stackexchange.com/questions/167582/why-zsh-ends-a-line-with-a-highlighted-percent-symbol 
    

    extract any file

    # extract files
    extract() {
    if [ -z ${1} ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
        echo "Usage: extract <archive> [directory]"
        echo "Example: extract presentation.zip."
        echo "Valid archive types are:"
        echo "tar.bz2, tar.gz, tar.xz, tar, bz2, gz, tbz2,"
        echo "tbz, tgz, lzo, rar, zip, 7z, xz, txz, lzma and tlz"
    else
        case "$1" in
            *.tar.bz2|*.tbz2|*.tbz)         tar xvjf "$1" ;;
            *.tgz)                          tar zxvf "$1" ;;
            *.tar.gz)                       tar xvzf "$1" ;;
            *.tar.xz)                       tar xvJf "$1" ;;
            *.tar)                          tar xvf "$1" ;;
            *.rar)                          7z x "$1" ;;
            *.zip)                          unzip "$1" ;;
            *.7z)                           7z x "$1" ;;
            *.lzo)                          lzop -d  "$1" ;;
            *.gz)                           gunzip "$1" ;;
            *.bz2)                          bunzip2 "$1" ;;
            *.Z)                            uncompress "$1" ;;
            *.xz|*.txz|*.lzma|*.tlz)        xz -d "$1" ;;
            *) echo "Sorry, '$1' could not be decompressed." ;;
        esac
    fi
    }
    

    fastest del dir (if you require to delete millions of directory)
    There are two methods perl one is faster than compare to rsync

    # delete dir with perl
    deldir(){
    currentdir=$PWD
    cd $1
    perl -e 'for(<*>){((stat)[9]<(unlink))}'
    cd "$currentdir"
    rm -r $1
    }
    
    # empyt large directory faster with rsync
    deldir(){
    mkdir /tmp/empty_dir
    rsync -avhP --delete /tmp/empty_dir/ "$1" | awk ' { printf ( "\r #%4d: %-200s", NR, $0 ) } '
    rm -r /tmp/empty_dir
    rm -r "$1"
    }
    

    AWS login with SSO and switch role
    change <initial-aws-profile> <ROLE-PROFILE-NAME> <ROLE-ACCOUNT-NO> <ROLE-NAME> <SESSION-NAME>

    aws-switch-role(){
    aws sso login --profile <initial-aws-profile>
    export AWS_PROFILE=<intial-aws-profile>
    aws sts get-caller-identity
    echo "Assuming role"
    sed -i -e '/<ROLE-PROFILE-NAME>/,+3d' ~/.aws/credentials
    aws sts assume-role --role-arn "arn:aws:iam::<ROLE-ACCOUNT-NO>:role/<ROLE-NAME>" --role-session-name <SESSION-NAME> | awk -F: '
                    BEGIN { RS = "[,{}]" ; print "[<ROLE-PROFILE-NAME>]"}
                    /:/{ gsub(/"/, "", $2) }
                    /AccessKeyId/{ print "aws_access_key_id = " $2 }
                    /SecretAccessKey/{ print "aws_secret_access_key = " $2 }
                    /SessionToken/{ print "aws_session_token = " $2 }
    ' >> ~/.aws/credentials
    export AWS_PROFILE=<ROLE-PROFILE-NAME>
    export AWS_CLI_AUTO_PROMPT=on-partial
    export AWS_REGION=eu-central-1
    aws sts get-caller-identity
    }
    

    youtube-dlp

    ## youtube-dl
    youtube2video() { 
            youtube-dlp \
                    -ciw \
                    -f 'bv*+ba/b' \
                    --merge-output-format mkv \
                    --add-metadata \
                    --replace-in-metadata 'title' '[^A-Za-z0-9]' '-' \
                    --replace-in-metadata 'title' '[-]{2,}' '-' \
                    --embed-thumbnail 
                    -o "~/Downloads/YouTube/Video/%(title)s-[%(id)s].%(ext)s" \
                    $@ ;
                    }
    
    youtube2audio() { 
            youtube-dlp \
            -ciw \
            -x -f bestaudio \
            -f m4a \
            --add-metadata \
            --replace-in-metadata 'title' '[^A-Za-z0-9]' '-' \
            --replace-in-metadata 'title' '[-]{2,}' '-' \
            --embed-thumbnail -o "~/Downloads/YouTube/Audio/%(title)s.%(ext)s" \
            $@ ;
            }
    
    youtube2audio_playlist() { 
            youtube-dlp \
            -ciw \
            -x -f bestaudio \
            -f m4a \
            --add-metadata \
            --replace-in-metadata 'title' '[^A-Za-z0-9]' '-' \
            --replace-in-metadata 'title' '[-]{2,}' '-' \
            --embed-thumbnail -o "~/Downloads/YouTube/Audio/%(title)s.%(ext)s" \
            --yes-playlist \
            $@ ;
            }
    
    youtube2audio_user_all_playlists() { 
            youtube-dlp \
            -ciw \
            -x -f bestaudio \
            -f m4a \
            --add-metadata \
            --replace-in-metadata 'title' '[^A-Za-z0-9]' '-' \
            --replace-in-metadata 'title' '[-]{2,}' '-' \
            --embed-thumbnail \
            -o "~/Downloads/YouTube/Audio/%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" \
            --yes-playlist \
            $@ ;
            }
    

    share file using terminal

    # upload file to transfer.sh
    transfer(){ if [ $# -eq 0 ];then echo "No arguments specified.\nUsage:\n transfer <file|directory>\n ... | transfer <file_name>">&2;return 1;fi;if tty -s;then file="$1";file_name=$(basename "$file");if [ ! -e "$file" ];then echo "$file: No such file or directory">&2;return 1;fi;if [ -d "$file" ];then file_name="$file_name.zip" ,;(cd "$file"&&zip -r -q - .)|curl --progress-bar --upload-file "-" "https://transfer.sh/$file_name"|tee /dev/null,;else cat "$file"|curl --progress-bar --upload-file "-" "https://transfer.sh/$file_name"|tee /dev/null;fi;else file_name=$1;curl --progress-bar --upload-file "-" "https://transfer.sh/$file_name"|tee /dev/null;fi;}
    

    git rename remote branch

    ## git rename branch
    git-rename-branch() {
    
    OLD_NAME="$1"
    NEW_NAME="$2"
    
    echo "\ncheckout $OLD_NAME\n"
    git checkout "$OLD_NAME"
    
    echo "\nRename the local branch to the new name\n"
    git branch -m "$OLD_NAME" "$NEW_NAME"
    
    echo "\nDelete the old branch on remote\n"
    git push origin --delete "$OLD_NAME"
    
    echo "\nPrevent git from using the old name when pushing in the next step.\
        \nOtherwise, git will use the old upstream name instead of $NEW_NAME.\n"
    git branch --unset-upstream "$NEW_NAME"
    
    echo "\nPush the new branch to remote\n"
    git push origin "$NEW_NAME"
    
    echo "\nReset the upstream branch for the new_name local branch\n"
    git push origin -u "$NEW_NAME"
    
    }
    
    ## clear terminal and buffer in osx
    alias cls='printf "\33c\e[3J"'
    
    Thanked by 1farsighter
  • eriseris Member
    edited October 2022
    if [ "${PATH#*/usr/local/hestia/bin*}" = "$PATH" ]; then
        . /etc/profile.d/hestia.sh
    fi
    

    Nothing special

  • Outputs Fail2Ban SSH ban count to console on login

    echo""
    echo "Fail2Ban SSH Bans"
    fail2ban-client status sshd | grep -i "Currently banned:"
    fail2ban-client status sshd | grep -i "Total banned:"
    echo""
    

    Or by command
    alias f2b="fail2ban-client status sshd | grep -i 'Total banned:' && fail2ban-client status sshd | grep -i 'Currently banned:'

    My current record holder

    Fail2Ban SSH Bans
       |- Currently banned: 16015
       |- Total banned:     16015
    
    Thanked by 1farsighter
  • lg=ls | grep
    
Sign In or Register to comment.