141

Is there anything that you can't live without and will make my life SO much easier? Here are some that I use ('diskspace' & 'folders' are particularly handy).

# some more ls aliases
alias ll='ls -alh'
alias la='ls -A'
alias l='ls -CFlh'
alias woo='fortune'
alias lsd="ls -alF | grep /$"

# This is GOLD for finding out what is taking so much space on your drives!
alias diskspace="du -S | sort -n -r |more"

# Command line mplayer movie watching for the win.
alias mp="mplayer -fs"

# Show me the size (sorted) of only the folders in this directory
alias folders="find . -maxdepth 1 -type d -print | xargs du -sk | sort -rn"

# This will keep you sane when you're about to smash the keyboard again.
alias frak="fortune"

# This is where you put your hand rolled scripts (remember to chmod them)
PATH="$HOME/bin:$PATH"
Hamish Downer
  • 9,142
  • 6
  • 36
  • 49
Gareth
  • 8,413
  • 13
  • 43
  • 44

39 Answers39

81

I have a little script that extracts archives, I found it somewhere on the net:

extract () {
   if [ -f $1 ] ; then
       case $1 in
           *.tar.bz2)   tar xvjf $1    ;;
           *.tar.gz)    tar xvzf $1    ;;
           *.bz2)       bunzip2 $1     ;;
           *.rar)       unrar x $1       ;;
           *.gz)        gunzip $1      ;;
           *.tar)       tar xvf $1     ;;
           *.tbz2)      tar xvjf $1    ;;
           *.tgz)       tar xvzf $1    ;;
           *.zip)       unzip $1       ;;
           *.Z)         uncompress $1  ;;
           *.7z)        7z x $1        ;;
           *)           echo "don't know how to extract '$1'..." ;;
       esac
   else
       echo "'$1' is not a valid file!"
   fi
 }
Gert M
  • 1,471
  • 1
  • 15
  • 14
  • 1
    Nice. Again though, there's that IDE/Vim argument regarding know the commands from memory. Fantastic bit of script though. Definitely going in the .bashrc Cheers! – Gareth May 05 '09 at 01:07
  • 19
    There's a nice and simple linux command called "unp", the Unpacker that does this and more. – Sander Marechal May 10 '09 at 23:33
  • The command has one missing feature. It cannot open 7z package at http://www.boost.org/doc/libs/1_39_0/more/getting_started/unix-variants.html correctly. Do you know how to solve the problem? – Léo Léopold Hertz 준영 Jun 02 '09 at 20:46
  • 7
    Newer versions of tar detect automatically the archive type, so can extract all supported formats by just 'tar xvf'. – Prof. Moriarty Jun 08 '10 at 17:47
  • @Sander dtrx isn't bad at that either. It makes sure the archive extracts to its own subdirectory. – Tobu Jul 02 '10 at 10:29
  • atool is a package that includes the commands apack and aunpack. They provide a convenient and consistent interface regardless of what the archive type is, and don't need any extra bash functions. – Matthew G Nov 23 '13 at 23:26
39

Since I use so many different machines, my .bashrc always sets the command prompt to include, among other things, the name of the server I am currently logged into. This way, when I am three levels deep in telnet/ssh, I don't type the wrong thing in the wrong window. It really sucks to rm -rf . in the wrong window! (Note: At home, telnet is disabled on all machines. At work, ssh is not always enabled and I don't have root access to very many machines.)

I have a script ~/bin/setprompt that is executed by my .bashrc, which contains:

RESET="\[\017\]"
NORMAL="\[\033[0m\]"
RED="\[\033[31;1m\]"
YELLOW="\[\033[33;1m\]"
WHITE="\[\033[37;1m\]"
SMILEY="${WHITE}:)${NORMAL}"
FROWNY="${RED}:(${NORMAL}"
SELECT="if [ \$? = 0 ]; then echo \"${SMILEY}\"; else echo \"${FROWNY}\"; fi"

# Throw it all together 
PS1="${RESET}${YELLOW}\h${NORMAL} \`${SELECT}\` ${YELLOW}>${NORMAL} "

This script sets the prompt to the host name followed by :) if the last command was successful and :( if the last command failed.

Eddie
  • 11,332
  • 8
  • 36
  • 48
25

Color for manpages in less makes manpages a little easier to read:

export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'

Colored manpages can also be obtained by installing most and using it as MANPAGER env variable. If you want to use this pager not only for man, use the PAGER variable, like this:

export PAGER="/usr/bin/most -s"
gene_wood
  • 483
  • 5
  • 15
oyvindio
  • 111
  • 1
  • 3
24

No more cd ../../../.. but up 4

Goes up many dirs as the number passed as argument, if none goes up by 1 by default (found in a link in a comment in stackoverflow.com and modified a bit)

up(){
  local d=""
  limit=$1
  for ((i=1 ; i <= limit ; i++))
    do
      d=$d/..
    done
  d=$(echo $d | sed 's/^\///')
  if [ -z "$d" ]; then
    d=..
  fi
  cd $d
}
  • This version of up() seems unnecessarily complex. I use this version: up() { cd $(eval printf '../'%.0s {1..$1}) && pwd; }. You can remove the call to 'pwd' if you wish obviously. – Matthew G Nov 26 '13 at 09:49
  • I use something like this: # Directory navigation aliases `alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..' alias .....='cd ../../../..'` – Matt Kenefick Oct 23 '14 at 18:39
19

I deal with a lot of different machines so one of my favorites is aliases for each machine that I need to frequently SSH to:

alias claudius="ssh dinomite@claudius"

It is also useful to setup a good .ssh/config and ssh keys to make hopping amongst machines even easier.

Another one of my favorite aliases is for moving up directories:

alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."

And some for commonly used variations of ls (and typos):

alias ll="ls -l"
alias lo="ls -o"
alias lh="ls -lh"
alias la="ls -la"
alias sl="ls"
alias l="ls"
alias s="ls"

History can be very useful, but by default on most distributions your history is blown away by each shell exiting, and it doesn't hold much to begin with. I like to have 10,000 lines of history:

export HISTFILESIZE=20000
export HISTSIZE=10000
shopt -s histappend
# Combine multiline commands into one in history
shopt -s cmdhist
# Ignore duplicates, ls without options and builtin commands
HISTCONTROL=ignoredups
export HISTIGNORE="&:ls:[bf]g:exit"

That way, if I know that I've done something before but can't remember the specifics, a quick history | grep foo will help jog my memory.

I often found myself piping output through awk in order to get a certain column of the output, as in df -h | awk '{print $2}' to find the size of each of my disks. To make this easier, I created a function fawk in my .bashrc:

function fawk {
    first="awk '{print "
    last="}'"
    cmd="${first}\$${1}${last}"
    eval $cmd
}

I can now run df -h|fawk 2 which saves a good bit of typing.

If you need to specify a delimiter (e.g., awk -F: for /etc/passwd), this function obviously can't handle that. The slightly-overhauled version in this gist can handle arbitrary awk arguments before the field number (but still requires input from stdin).

Drew Stephens
  • 662
  • 7
  • 12
15

GPG encrypted bashrc

I'm sure we all have things we'd like to put in our bashrc that we don't want easily readable by sudoers. My solution to this is:

if [ -f ~/.bash_private.gpg ]; then
   eval "$(gpg --decrypt ~/.bash_private.gpg 2>/dev/null)"
fi

I have a GPG agent that makes it so I only have to enter my private key's password once every few hours. You still have to have some trust in the users of the system because your variable, functions, and aliases that you define could be extracted from RAM. However, I use this mainly for my laptop. If it gets stolen, I don't want someone easily seeing things like:

alias MYsql='mysql -uadmin -psecret'
wglatest(){ wget -O https://admin:secret@server.com/latest; }
Bruno Bronosky
  • 4,429
  • 3
  • 24
  • 32
  • Do you also encrypt your history in that case? Why not encrypt your $home – Rqomey Jul 04 '12 at 15:10
  • @Rqomey, the whole point is that I don't have to encrypt my history as my passwords do not show up in my .bash_history because they are hidden by aliases or functions. In it you see things like `MYsql < garbagecollect.sql` instead of `mysql -uadmin -psecret < garbagecollect.sql` – Bruno Bronosky Apr 05 '13 at 18:54
12

I used to set these up all over the place but then realized that it was better to just remember how to do them 'manually' because it meant I would 1) fully understand what was going on and 2) have access to these capabilities even if my custom .bashrc wasn't installed.

The only thing I use aliases for these days are to cut down on repetitive typing of really long lines (eg. alias myhost='ssh -T user@my.remote.host screen -dAr' )

pjz
  • 10,497
  • 1
  • 31
  • 40
  • 2
    Agreed regarding memorising long useful commands. I find though that I'm running 'diskspace' fairly often on runaway servers (i.e. php is coredumping all over the place). – Gareth May 04 '09 at 01:24
  • yeah, I actually have something similar to that (du /home/* --max-depth 1 | sort -n >/home/.sizes ) run nightly so I can keep a rough eye on my users' space consumption on the big shared machine. – pjz May 04 '09 at 01:36
  • 1
    It's easy enough to deploy your custom configuration on systems you regularly use, though. – Tobu Nov 15 '10 at 17:59
  • Just as a follow up to you ssh alias, this is something I do all the time. I always do this with the IP though in case of DNS outage. – jwbensley May 11 '13 at 13:52
12

this is an awesome resource for this:

show us your .bashrc

devin
  • 1,226
  • 3
  • 20
  • 27
9

The one liners and tiny scripts out there could go on forever. I recommend man bash and writing things yourself. Some good short bash stuff at http://www.commandlinefu.com. Heres a few things.

#use extra globing features. See man bash, search extglob.
shopt -s extglob
#include .files when globbing.
shopt -s dotglob
#When a glob expands to nothing, make it an empty string instead of the literal characters.
shopt -s nullglob
# fix spelling errors for cd, only in interactive shell
shopt -s cdspell
# vi mode
set -o vi

s() { # do sudo, or sudo the last command if no argument given
    if [[ $# == 0 ]]; then
        sudo $(history -p '!!')
    else
        sudo "$@"
    fi
}

prompt_command() {
    p=$PWD  # p is much easier to type in interactive shells
    # a special IFS should be limited to 1 liners or inside scripts.
    # Otherwise it only causes mistakes.
    unset IFS
}
PROMPT_COMMAND=prompt_command


# smart advanced completion, download from
# http://bash-completion.alioth.debian.org/
if [[ -f $HOME/local/bin/bash_completion ]]; then
    . $HOME/local/bin/bash_completion
fi


extract () { # extract files. Ignore files with improper extensions.
    local x
    ee() { # echo and execute
        echo "$@"
        $1 "$2"
    }
    for x in "$@"; do
        [[ -f $x ]] || continue
        case "$x" in
            *.tar.bz2 | *.tbz2 )    ee "tar xvjf" "$x"  ;;
            *.tar.gz | *.tgz ) ee "tar xvzf" "$x"   ;;
            *.bz2 )             ee "bunzip2" "$x"   ;;
            *.rar )             ee "unrar x" "$x"   ;;
            *.gz )              ee "gunzip" "$x"    ;;
            *.tar )             ee "tar xvf" "$x"   ;;
            *.zip )             ee "unzip" "$x"     ;;
            *.Z )               ee "uncompress" "$x" ;;
            *.7z )              ee "7z x" "$x"      ;;
        esac
    done
}
Ian Kelling
  • 2,661
  • 6
  • 23
  • 21
9

A little tip for Bash if you are a sysadmin and work with root privileges a lot:

shopt -o noclobber

This will prevent you from accidentally destroying the content of an already existing file if you redirect output (>filename). You can always force overwriting with >|filename.

Cyberdrow
  • 271
  • 1
  • 4
8

I have the following in my bashrc

function __setprompt {
  local BLUE="\[\033[0;34m\]"
  local NO_COLOUR="\[\033[0m\]"
  local SSH_IP=`echo $SSH_CLIENT | awk '{ print $1 }'`
  local SSH2_IP=`echo $SSH2_CLIENT | awk '{ print $1 }'`
  if [ $SSH2_IP ] || [ $SSH_IP ] ; then
    local SSH_FLAG="@\h"
  fi
  PS1="$BLUE[\$(date +%H:%M)][\u$SSH_FLAG:\w]\\$ $NO_COLOUR"
  PS2="$BLUE>$NO_COLOUR "
  PS4='$BLUE+$NO_COLOUR '
}
__setprompt

On a local machine it looks like:

[17:57][user:~]$

but on a remote (through ssh) it is:

[17:57][user@machine:~]$
6

I've had this in my .bashrc for a while and I've found it helpful. If you are sshing in to the box, is starts screen automatically when you login, that way when your network connection gets interrupted or whatever, you don't lose whatever you were doing. It should be placed at the end.

if [ "$PS1" != "" -a "${STARTED_SCREEN:-x}" = x  -a "${SSH_TTY:-x}" != x ]
then
STARTED_SCREEN=1 ; export STARTED_SCREEN
[ -d $HOME/lib/screen-logs ] || mkdir -p $HOME/lib/screen-logs

sleep 1
screen -U -RR && exit 0

echo "Screen failed! continuing with normal bash startup"
fi
baudtack
  • 490
  • 1
  • 6
  • 15
  • If you set your login shell to be screen (and configure e.g. bash in your .screenrc), then whenever you SSH in, screen will automatically try to reconnect to disconnected screens. If that fails, it will create a new screen. – Dan Udey May 17 '09 at 18:10
  • @Dan Udey I haven't tried what you suggested myself, but the bash I posted will start the screen only on ssh logins were as setting screen as your login shell, would also start it on local logins. Which maybe what you want. It's just not what I want. :-) – baudtack May 21 '09 at 22:07
  • If you are worried about disconnects, check out mosh, I use it all the time and highly recommend it: http://mosh.mit.edu/ – jwbensley May 11 '13 at 14:10
5

Tail all logs in /var/log

alias logs="find /var/log -type f -exec file {} \; | grep 'text' | cut -d' ' -f1 | sed -e's/:$//g' | grep -v '[0-9]$' | xargs tail -f"
hoberion
  • 231
  • 2
  • 15
5

How many aliases to fortune do you need, anyway?

I like to make a cdd alias that takes me to wherever I'm presently most likely to be working on that server.

PATH redefinition really belongs in .bash_profile, not .bashrc.

On a server where I routinely use a large set of screens, my .bashrc will have:

alias s1="screen -dr chaos1"
alias s2="screen -dr chaos2"
alias s3="screen -dr chaos3"
# ... and so on

(The screens were set up with, for example, screen -U -S chaos1.)

chaos
  • 7,463
  • 4
  • 33
  • 49
  • 2
    @chaos "How many aliases to fortune do you need, anyway?". woo for win. frak(and alternate spellings) for fail. – Gareth May 04 '09 at 00:56
  • Please follow these steps. 1) Extend your PATH in your .bashrc. 2) Type 'bash'. 3) Type 'echo $PATH'. 4) Type 'bash'. 5) Type 'echo $PATH'. 6) Punch yourself in the head for ignorantly downvoting and insulting people because they know more about sysadmin best practices than you. – chaos May 04 '09 at 06:49
  • I am impressed that you have a slightly valid reason, not going to punch myself in the face though. Its easy to get non-login shells where your path was not already extended. I take back that its dumb, I originally read it that you were trying to say you should not set important variables in your .bashrc or something. – Ian Kelling May 04 '09 at 07:33
  • Perhaps someone should start a "Should I set my PATH variables in the .bashrc or .bash_profile"? – Gareth May 04 '09 at 08:03
  • 3
    @Ian Kelling: What I'm actually saying is that operations that should be performed once per login belong in .bash_profile and operations that should be performed once per shell instantiation belong in .bashrc. – chaos May 04 '09 at 11:43
5

Among other things, I set some defaults for less, prevent accidentally closing my terminal and enable forward navigation through history:

# ignore case, long prompt, exit if it fits on one screen, allow colors for ls and grep colors
export LESS="-iMFXR"

# must press ctrl-D 2+1 times to exit shell
export IGNOREEOF="2"

# allow ctrl-S for history navigation (with ctrl-R)
stty -ixon
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148
5

I have a few bits:

# stop the pc speaker ever annoying me :)
setterm -bfreq 0

# don't put duplicate lines in the history. See bash(1) for more options
HISTCONTROL=ignoredups
# ... and ignore same sucessive entries.
HISTCONTROL=ignoreboth

# Expand the history size
HISTFILESIZE=10000 
HISTSIZE=100

# commands with leading space do not get added to history
HISTCONTROL=ignorespace

# am I on the internet?
alias p4='ping 4.2.2.2 -c 4'

# pwsafe
alias pw='pwsafe -p'

# ls aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias lt='ls -laptr' #oldest first sort
alias labc='ls -lap' #alphabetical sort

# cd aliases
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'

# cd into the old directory
alias bd='cd "$OLDPWD"'

# install a package and automatically respond yes to confirmation prompt
alias ins="sudo aptitude install"

# remove a package and its configuration files
alias remp="sudo aptitude purge"

# search for a package - apt-cache and aptitude search in different ways
# so have both
alias searchc="apt-cache search"
alias search="aptitude search"
alias show="aptitude show"
Hamish Downer
  • 9,142
  • 6
  • 36
  • 49
4

To have colors for All grep commands such as grep, egrep and zgrep, I have the following in my .bashrc

export GREP_OPTIONS='--color=auto'
4

The 'folders' alias is great! I modified it slightly so that directories with spaces don't cause errors.

alias folders='find . -maxdepth 1 -type d -print0 | xargs -0 du -sk | sort -rn'
Andrew
  • 7,772
  • 3
  • 34
  • 43
phoenix8
  • 213
  • 2
  • 9
3

Shell-fu.org's .bashrc collection

raspi
  • 811
  • 1
  • 9
  • 21
3

Here are mines:

export HISTCONTROL=ignoredups
export HISTIGNORE="&:ls:bg:fg"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# shows you if you are in a chroot or in a git repository
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;30m\]\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]$(__git_ps1)\$ '


if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

# two handy single-letter aliases

alias u='ls -hltr'
alias e='du * -cs | sort -nr | head'
alias g='grep -C5 --color=auto'

# creates a temp dir and cds into it
alias td='pushd $(mktemp -d)'

# find <dir> <file name regexp> <file contents regexp>
function fing { find "$1" -name "$2" -exec grep -H "$3" "{}" \; }

# shows "git diff" across any project in any subdirectory
alias git-differ='for g in $(find . -name ".git"); do g=${g%%.git};printf "$g\t\t\t";pu $g >/dev/null && git diff |wc -l; p >/dev/null; done'

# does git house keeping across any project in any subdirectory
alias git-housekeep='for g in $(find . -name ".git"); do g=${g%%.git};echo $g;pu $g && git repack && git gc --auto && p;done'

# Debian update
alias apg='aptitude update && aptitude dist-upgrade && aptitude clean'

# Quick way to serve files in HTTP from the local dir
alias webs='python -m SimpleHTTPServer'
Federico
  • 351
  • 2
  • 7
3

I would echo @pjz's comment about knowing things manually rather than setting them up. Especially if you access numerous machines, like I always seem to do.

So one I definitely know is set -o vi because I know the vi-editing commands in bash and I don't know the emacs ones (besides, Ctrl+A interferes with screen). On my own boxes, I put that in .bashrc

I also find I have to include export EDITOR=vim because a number of recent distros default to nano which is most annoying to be thrown into by a utility that needs you to edit something, when I was expecting vi. :-/

I also alter my prompt. I found a long long time ago that adding the last error code is just useful enough that I like it. And I like the full pathname in the prompt. And the current screen number, too. And it just makes sense to include the current user and hostname. My prompt is PS1='\u@\h $PWD $WINDOW [$?] \$ '

staticsan
  • 1,529
  • 1
  • 11
  • 14
3

Have bash check to see if the window size has changed (prevents line-editing from going weird if you resize your terminal window)

shopt -s checkwinsize

This is my favourite. Causes bash to append to history instead of overwriting it. Typically when you launch bash, it loads history into memory, and when you close it it writes it out. This means that if you load two shells, use both, then close both, the one you closed last overwrites all changes.

This snippet causes it to first of all only append changes (instead of overwriting with the whole buffer), and then to cause it to, after every command, write out changes. In effect, you get a live updating .bash_history, so if you start a new terminal, you have all the commands from your other running sessions' history.

shopt -s histappend
PROMPT_COMMAND='history -a'
Dan Udey
  • 1,460
  • 12
  • 17
2

Here are a few of my favorites:

alias ls='ls -F --color=auto'
alias l='ls'
alias ll='ls -ahl'
alias ..='cd ..'
alias ...='cd ../..'
alias mv='mv -i'

mkcd() {
        if [ $# != 1 ]; then
                echo "Usage: mkcd <dir>"
        else
                mkdir -p $1 && cd $1
        fi
}

# Git related
alias gs='git status'
alias gc='git commit'
alias ga='git add'
alias gd='git diff'
alias gb='git branch'
alias gl='git log'
alias gsb='git show-branch'
alias gco='git checkout'
alias gg='git grep'
alias gk='gitk --all'
alias gr='git rebase'
alias gri='git rebase --interactive'
alias gcp='git cherry-pick'
alias grm='git rm'
2

These are my favorites:

export HISTFILESIZE=1000000000
export HISTSIZE=1000000

I like having a command-line history that never forgets.

Unfortunately, awhile back I launched a shell from cron which didn't read .bashrc somehow, and chopped everything down to 500 lines, destroying over a years' history. So I recommend these go in /etc/bashrc.

skiphoppy
  • 181
  • 2
  • 6
2

From Automating Linux and Unix Administration by Kirk Bauer (great book!)

PS1='\n[\u@\h]: \w\n$?> '

The newline at the beginning is mine, I like to have a clear line between the previous output and the prompt. The rest is:

\u = username

\h = host

\w = working directory

$? = last return code

2

I use this about 20 times a day to cd into the last changed directory:

cl()
{
        last_dir="$(ls -Frt | grep '/$' | tail -n1)"
        if [ -d "$last_dir" ]; then
                cd "$last_dir"
        fi
}

These two keep permanent bookmarks of often used directories:

rd(){
    pwd > "$HOME/.lastdir_$1"
}

crd(){
        lastdir="$(cat "$HOME/.lastdir_$1")">/dev/null 2>&1
        if [ -d "$lastdir" ]; then
                cd "$lastdir"
        else
                echo "no existing directory stored in buffer $1">&2
        fi
}
1

I use my bashrc on numerous machines, so i've got this little snippet to make sure LS is colourized. This will fix it on OSX machines, maybe even *BSD if you adjust the uname line.

if [ "$TERM" != "dumb" ]; then
    if [ `uname` == "Darwin" ]; then
       alias ls='ls -G'
    else
       eval "`dircolors -b`"
       alias ls='ls --color=auto'
    fi
fi

Also, I've got a command to backup a file, useful if your about to change a config file and want to make a quick copy before hand.

bu () { cp $1 ~/.backup/`basename $1`-`date +%Y%m%d%H%M`.backup ; }
Andrew Williams
  • 667
  • 8
  • 20
1

This is one of my favorites:

alias ssh='if [ "$(ssh-add -l)" = "The agent has no identities." ]; then ssh-add; fi; /usr/bin/ssh "$@"'

If i've forgotten to authenticate, it lets me do so without having to waste my typing doing ssh-add after the ssh session.

joshk0
  • 465
  • 2
  • 5
1

A couple good ones

Make SSH automatically complete the hostname you ssh to (if it's in your config or history)

complete -o default -o nospace -W "$(/usr/bin/env ruby -ne 'puts $_.split(/[,\s]+/)[1..-1].reject{|host| host.match(/\*|\?/)} if $_.match(/^\s*Host\s+/);' < $HOME/.ssh/config)" scp sftp ssh

Some useful bash completion settings

bind "set completion-ignore-case on" # note: bind used instead of sticking these in .inputrc
bind "set bell-style none" # no bell
bind "set show-all-if-ambiguous On" # show list automatically, without double tab

Some useful ones for Mac OS X

alias nospotlight='sudo mdutil -a -i off'
alias cleardnscache='sudo killall -HUP mDNSResponder'
alias ldd='otool -L'
alias seq='jot - '
alias eject='drutil eject'
lynxman
  • 9,157
  • 3
  • 24
  • 28
1
IP_ADDRESS_BASH=`ip addr | grep -w inet | gawk '{if (NR==2) {$0=$2; gsub(/\//," "); print $1;}}'`
PS1="\h $IP_ADDRESS_BASH \w % "

And then it displays IP of your machine that you just logged to.

mrkafk
  • 379
  • 1
  • 2
  • 7
1
# vi ~/.bashrc # red/green terminal colors regarding exit code
export PROMPT_COMMAND='PS1="`
if [[ \$? = "0" ]];
then echo "\\[\\033[0;32m\\]";
else echo "\\[\\033[0;31m\\]";
fi`[\u@\h \w]\[\e[m\] "'
export PS1
LanceBaynes
  • 2,907
  • 9
  • 27
  • 31
  • Will this alter the $? variable after running the command or does it still have the value produced by the last command run? – Andrew Case Jun 28 '12 at 05:00
1
mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }

ecb () { emacsclient -n -a emacs $@ & } # open in emacsclient in the background
ecp () { emacsclient -n $(which $@) & } # open a given file found in a $PATH in emacsclient
ecr () { SUDO_EDITOR="emacsclient -a emacs" sudoedit $@; } # start emacsclient or emacs and open the file as root

eCf () { emacs --batch --eval "(byte-compile-file \"$@\")"; } # byte-compile file
eCa () { emacs --batch --eval "(batch-byte-compile-if-not-done)" *.el; } # byte-compile all el files in the current directory and it's children
Adobe
  • 119
  • 7
1

I compile a number of things manually into $HOME/local so I have this little snippet:

for prog in $HOME/local/*
do
    if [ -d "$prog/bin" ]; then
        export PATH=$prog/bin:$PATH
    fi
    if [ -d "$prog/include" ]; then
        export C_INCLUDE_PATH=$prog/include:$C_INCLUDE_PATH
    fi
    if [ -d "$prog/lib" ]; then
        export LD_LIBRARY_PATH=$prog/lib:$LD_LIBRARY_PATH
        export LIBRARY_PATH=$prog/lib:$LIBRARY_PATH
    fi
    if [ -d "$prog/man" ]; then
        export MANPATH=$prog/man:$MANPATH
    fi
    if [ -d "$prog/share/man" ]; then
        export MANPATH=$prog/share/man:$MANPATH
    fi
done

I also have my IRC client on my server running in screen so I have this (not a .bashrc thing, but still useful)

#!/usr/bin/env bash

RUNNING=`screen -ls | grep irc`
if [ "" = "$RUNNING" ]; then
   screen -S irc irssi
else
   screen -dr irc
fi
Daniel Huckstep
  • 529
  • 2
  • 8
  • 18
0

. $HOME/bin/git-prompt/git-prompt.sh

bbigras
  • 276
  • 1
  • 7
0

A few aliases I use to take the edge off of the daily CLI grind...

# I find myself doing this a lot
alias hg='history | grep '

# Likewise this, plus I'm always mistyping it...
alias findy='find . -name'

# sometimes you're just not sure you want to delete something...
alias trash='mv -t ~/.local/share/Trash/files --backup=t'

alias vb='vim ~/.bashrc'

# I find typing 'cd ..' less than optimal
alias up='cd ..'
alias 2up='cd ../../'
alias 3up='cd ../../../'
alias 4up='cd ../../../../'

# re-map caps lock key to be Ctrl
# (works on Linux, at least)
xmodmap -e "remove lock = Caps_Lock"
xmodmap -e "add control = Caps_Lock"

# helpful history settings:
export HISTCONTROL=ignoredups
export HISTCONTROL=ignoreboth
export HISTIGNORE=ls:ll:la:l:cd:pwd:exit:mc:su:df:clear:cls
yalestar
  • 227
  • 1
  • 2
  • 7
  • You could make 1up print a mushroom in ASCII art, just for kicks ;) – David Z Jun 30 '09 at 19:00
  • While almost all of the answers refer to tweaking history, I haven't seen any which enable timestamping which can be useful. `export HISTTIMEFORMAT='%F %T '` – cclark Aug 01 '12 at 17:45
0

To fix window size in GNU screen after resize:

shopt -s checkwinsize

To show the permissions on a directory, shortcut ls -ld:

alias lld='ls -ld'

History viewing:

alias h='history | zgrep'

And contents of my zgrep script, which I couldn't figure out how to cram directly into the alias:

#!/bin/sh
grep "${*-.}"
0

I'm addicted to screen, and I use the following shortcuts for SSHing to machines. With this script, I type p hostname to SSH to a host and run screen, or o hostname to do the same but run screen on the local machine.

First a script that connects to an SSH server of the same name as the script you're running. I call this simple_ssh:

#!/bin/sh
BASENAME=$(basename $0)

if [ "$SCREEN" = "1" ]; then
    export SCREEN=0
    exec screen -RD scr$BASENAME -s $0
elif [ "$SCREEN" = "2" ]; then
    exec ssh $BASENAME "$@" -t 'screen -RD'
fi

exec ssh $BASENAME "$@"

Symlink this to mars in your path and mars becomes a shortcut for ssh mars:

adam@pluto:bin$ ln -s simple_ssh mars
adam@pluto:bin$ mars
adam@mars:~$

The $SCREEN environment variable lets you automatically execute GNU screen with the connection. SCREEN=1 runs screen locally (say, if screen is not installed on the host) and SCREEN=2 runs it on the host itself.

Use a couple aliases to shortcut this:

alias o='SCREEN=1 exec'
alias p='SCREEN=2 exec'

Use a script to create symlinks for all your hosts given an ~/.ssh/config file like this:

Host mars
    HostName mars.example.com
    User abackstrom

The script, sshconfig2simplessh:

#!/bin/sh

BASENAME=$(basename "$0")
USAGE="Usage: $BASENAME /path/to/bin"

if [ -z "$1" ] ; then
    echo $USAGE
    exit 0
fi

if [ ! -d "$1" ] ; then
    echo "$1 is not a directory" >&2
    exit 1
fi

cd "$1"

HOSTS=$(grep '^Host ' < ~/.ssh/config | cut -d' ' -f2)

for HOST in $HOSTS ; do
    if [ ! -e "$HOST" ]; then
        echo ln -s simple_ssh "$HOST"
        ln -s simple_ssh "$HOST"
    fi
done
0

Fedora

alias install=sudo yum install

Debian

alias install=sudo apt-get update && sudo apt-get install
egorgry
  • 2,871
  • 2
  • 22
  • 21
0

I sometimes have to use a Solaris system at work.

However the system is centrally managed via Puppet, including the password file (which includes the shell setting).

My .bashrc therefore reads something like:

%!/bin/bash
exec /bin/tcsh

:)

Alnitak
  • 20,901
  • 3
  • 48
  • 81