Page 1 of 6 123 ... LastLast
Results 1 to 10 of 51

Thread: Handy command-line aliases and tricks

  1. #1
    Join Date
    Jun 2006
    Location
    Gwangju, Korea
    Beans
    3,479

    Lightbulb Handy command-line aliases and tricks

    I often find that filesystem tasks are quicker from the command line. So, I've compiled some of my favorite aliases and tricks. Note that these have only been tested in bash (bash is the default shell--or command interpreter--in most flavors of Linux, including Ubuntu).

    Command Editing
    Tab completion: type part of a command name or filename and hit tab. Bash will automatically fill in as much as it can unambiguously. If you hit tab twice, bash will show you a list of commands/filenames that match what you've typed so far.

    Searching through your history: If you hit ^R (Ctrl+R) then start typing, bash will display the last match from your command history. Hit enter to execute the displayed command, left or right arrow to edit the command, or ^C to cancel.

    Job Control
    Typing ^Z stops a program without exiting and gives you back a command line. You can use this to do several things at once. Type fg to bring the program back to the front or bg to tell it to resume in the background. Append an ampersand (&) to the end of a command to start a program in the background. Type jobs for a list of current jobs.

    Quote Originally Posted by userundefine View Post
    Let's not forget to mention one of the greatest tips -- how to cancel any running program in CLI ! Ctrl+C.
    Aliases
    Aliases are shortcuts to commands you use often. They can save you from having to remember certain options that you usually use. To create an alias, type alias alias_name='aliased_command --options', making substitutions where appropriate. type unalias alias_name to remove an alias and alias without any options to see the aliases that are currently defined.

    Examples: Here are some of the aliases I use.
    Code:
    #Aliases for improved directory listings
    #The --color=tty option shows items in different colors according to their type.
    #For example, directories are blue, executable files are green, symlinks are cyan, etc.
    #The -F option appends a symbol after entries to indicate their types.
    #You might not like both options at the same time.
    alias ls='ls -F --color=tty' #regular ls
    alias l.='ls -dF .[a-zA-Z0-9]* --color=tty' #only show dotfiles
    alias ll='ls -lhF --color=tty' #long listing
    
    #Make these commands ask before clobbering a file. Use -f to override.
    alias rm="rm -i"
    alias cp="cp -i"
    alias mv="mv -i"
    
    #Use human-readable filesizes
    alias du="du -h"
    alias df="df -h"
    
    #Miscellaneous
    alias bzip2='bzip2 -v'
    alias j=jobs
    alias cd..="cd .." #work around a common typo
    
    #Automatically do an ls after each cd
    cd() {
      if [ -n "$1" ]; then
        builtin cd "$@" && ls
      else
        builtin cd ~ && ls
      fi
    }
    Saving for future use: There are a number of ways to do this, but the way I prefer is to create a file in your home directory called .alias and put all your aliases there. Then insert the following at the end of $HOME/.bashrc
    Code:
    # Source the aliases, if a separate file exists
    if [ -e $HOME/.alias ]; then
      [ -n "$PS1" ] && . $HOME/.alias
    fi
    To apply your changes to the current session, type source $HOME/.bashrc

    Setting the Prompt
    You can change your prompt by setting $PS1 and $PS2 in ~/.bashrc. There are many ways to do this. Here's what I have in my .bashrc:
    Code:
    # Set the prompt
    function setPrompt {
      local COLOR1="\[\033[1;33m\]"     #First color
      local COLOR2="\[\033[0;33m\]"     #Second color
      local NO_COLOR="\[\033[0m\]"      #Transparent - don't change
    
      case $TERM in
        xterm*)
          local TITLEBAR="\[\033]0;\h - \w\007\]"
          ;;
        *)
          local TITLEBAR=""
          ;;
      esac
    
      PS1="${TITLEBAR}${COLOR1}\w${COLOR2}:\\$ ${NO_COLOR}"
      PS2="${COLOR2}--${COLOR1}> ${NO_COLOR}"
    }
    
    setPrompt
    unset setPrompt
    I set different colors for different machines. For example, I have
    Code:
    local COLOR1="\[\033[1;32m\]"
    local COLOR2="\[\033[1;34m\]"
    on my server and
    Code:
    local COLOR1="\[\033[7;1;31m\]"
    local COLOR2="\[\033[7;1;31m\]"
    for my root prompt. For root, I also set
    Code:
    local TITLEBAR="\[\033]0;ROOT - \w - \u@\h - ROOT\007\]"
    Attached is a script that lists some of the various color codes.

    Exit status: In addition, the following code displays the exit status of the last command, if nonzero:
    Code:
    #Not my code; I don't remember where I got it.
    #Determine and display the exit Status of the last command, if non-zero.
    function checkExitStatus() {
      local status="$?"
      local signal=""
      local COLOR1="\033[0;0;33m"     #First color
      local COLOR2="\033[0;0;36m"     #Second color
      local NO_COLOR="\033[0m"        #Transparent - don't change
    
      if [ ${status} -ne 0 -a ${status} != 128 ]; then
        # If process exited by a signal, determine name of signal.
        if [ ${status} -gt 128 ]; then
          signal="$(builtin kill -l $((${status} - 128)) 2>/dev/null)"
          if [ "$signal" ]; then
            signal="$signal"
          fi
        fi
        echo -e "${COLOR1}[Exit ${COLOR2}${status} ${signal}${COLOR1}]${NO_COLOR}" 1>&2 ${COLOR2}${signal}${COLOR1}]${NO_COLOR} " 1>&2
        fi
      return 0
    }
    
    PROMPT_COMMAND=checkExitStatus
    Scripts
    Here are a couple of other scripts that are handy:

    Listing processes: This script is a shortcut to ps -ef | grep foo. Save in in your path as p and make it executable. For usage instructions, type p --help.
    Code:
    #!/bin/bash
    #
    # Shortcut to ps -ef | grep foo
    
    GREP="|grep"
    CMD="ps -ef"
    CMD2=
    finalStr=
    commandStr="/bin/bash $0"
    
    printHelp() {
        echo -e "Shortcut to \"ps -ef | grep foo\"\n"
        echo "Usage: $(basename "$0") [-i] [-v] pattern1 [pattern2 [pattern3 [...]]]"
        echo "-i: case-insensitive grep"
        echo "-v: inverse grep: return lines that do NOT match the pattern"
        exit
    }
    
    for i in "$@"; do commandStr="$commandStr $i"; done
    
    for i in "$@"; do
        getopts ivh option
        if   [ $option == i ]; then GREP="${GREP} -i"
        elif [ $option == v ]; then GREP="${GREP} -v"
        elif [ $option == h -o "$i" == "--help" ]; then printHelp; fi
    done
    
    for i in "$@"; do
        if [ "$i" == "-i" -o "$i" == "-v" -o "$i" == "-vi" -o "$i" == "-iv" ]; then shift
        else break; fi
    done
    
    for i in "$@"; do CMD2="${CMD2}${GREP} \"$i\""; done
    
    finalStr="${CMD}${CMD2} | grep -v 'ps -ef' | grep -v ' grep ' | grep -v '/grep ' | grep -v '$commandStr'"
    
    eval $finalStr
    Recursive Shredding: The shred command securely erases files. Great. But it doesn't work recursively (you can't give it a directory, for example). This script does. Save in in your path and make it executable. Do name_you_called_it --help for instructions.
    Code:
    #!/bin/bash
    
    EXIT_VAL=0
    progName="$(basename "$0")"
    verStr="Recursive Shredder 0.1"
    
    FILE_COLOR="\033[4;34m"
    ERROR_COLOR="\033[0;31m"
    DONE_COLOR="\033[0;32m"
    NO_COLOR="\033[0m" #Transparent - don't change
    
    licTxt() {
        echo "Copyright (c) 2006 by Scott Severance"
        echo "Licensed under the terms of the GNU General Public License"
        echo
        echo "This software is provided \"AS-IS\" and carries NO WARRANTY. Use it at your own risk."
    }
    
    shredThis() {
        #echo "press any key"
        #read -sn 1
        if [ -d "$1" -a "$1" != "." -a "$1" != ".." ]; then
            local oldDir="$(pwd)"
            builtin cd "$1"
            echo -e "Entering directory: ${FILE_COLOR}$(pwd)${NO_COLOR}"
            #pwd
            for i in * .*; do
                if [ "$i" != "." -a "$i" != ".." -a "$i" != "*" ]; then
                    shredThis "$i"
                fi
                done
            builtin cd "$oldDir"
            echo -e "Removing directory: ${FILE_COLOR}${1}${NO_COLOR}"
            echo -ne $ERROR_COLOR
            rmdir "$1"
            echo -ne $NO_COLOR
            #echo -n "Returning to "
            #pwd
        
    
        elif [ -L "$1" -o -p "$1" -o -S "$1" ]; then # test for symlinks, fifos, and sockets
            echo -ne "Deleting special file ${FILE_COLOR}${1}${NO_COLOR}... "
            echo -ne $ERROR_COLOR
            rm "$1"
            echo -ne $NO_COLOR
            local rslt="$?"
            if [ "$rslt" -ne "0" ]; then
                echo -e "${ERROR_COLOR}### ERROR deleting ${FILE_COLOR}${1}${ERROR_COLOR}: rm exited with status ${rslt}. Aborting. ###${NO_COLOR}" > /dev/stderr
                exit 127
            fi
            echo -e "${DONE_COLOR}Done${NO_COLOR}"
    
         elif [ -f "$1" ]; then
            echo -ne "Shredding ${FILE_COLOR}${1}${NO_COLOR}... "
            echo -ne $ERROR_COLOR
            shred --zero --remove "$1"
            echo -ne $NO_COLOR
            local rslt="$?"
            if [ "$rslt" -ne "0" ]; then
                echo -e "${ERROR_COLOR}### ERROR shredding ${FILE_COLOR}${1}{$ERROR_COLOR}: shred exited with status ${rslt}. Aborting. ###${NO_COLOR}" > /dev/stderr
                exit 127
            fi
            echo -e "${DONE_COLOR}Done${NO_COLOR}"
    
        else
            echo -e "${ERROR_COLOR}### NOTICE: The file ${FILE_COLOR}${1}${ERROR_COLOR} is not a regular file. Skipping. ###${NO_COLOR}" > /dev/stderr
            EXIT_VAL=3
        fi
    }
    
    if [ "$1" = "--no-color" ]; then
        FILE_COLOR=""
        ERROR_COLOR=""
        DONE_COLOR=""
        NO_COLOR=""
        shift
    fi
    
    if [ "$#" = "0" -o "$1" = "--help" ]; then
        echo -e "${DONE_COLOR}${verStr}${NO_COLOR}" > /dev/stderr
        echo > /dev/stderr
        echo "Usage: $progName [--no-color] file-or-directory-1 file-or-directory-2 ..." > /dev/stderr
        echo "       $progName --help" > /dev/stderr
        echo "       $progName --version" > /dev/stderr
        EXIT_VAL=1
    
    elif [ "$1" = "--version" ]; then
        echo -e "${DONE_COLOR}${verStr}${NO_COLOR}"
        echo
        licTxt
        EXIT_VAL=2
    
    else
        for i in "$@"; do
            if [ "$i" = "." ]; then i="$(pwd)"; fi
            shredThis "$i"
        done
    fi
    
    exit $EXIT_VAL
    Other Tips
    If you have any other aliases, etc. that might be useful to others, please add them here.
    Last edited by mssever; November 30th, 2007 at 09:43 AM. Reason: typo

  2. #2
    Join Date
    May 2006
    Location
    Planet Earth
    Beans
    102
    Distro
    Kubuntu 6.10 Edgy

    Re: Handy command-line aliases and tricks

    Thank you. The alias cd..=cd .. is really handy. Don't know why I couldn't think of that.

  3. #3
    Join Date
    Jun 2006
    Location
    Värmland
    Beans
    23
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    Re: Handy command-line aliases and tricks

    i find
    Code:
    df='df -h'
    ls='ls -hal'
    du='du -sh'
    very usefull

  4. #4
    Join Date
    Oct 2005
    Location
    London
    Beans
    305

    Re: Handy command-line aliases and tricks

    My aliases:
    alias agi='sudo apt-get install'
    alias agr='sudo apt-get remove'
    alias agu='sudo apt-get update'
    alias agdu='sudo apt-get dist-upgrade'
    alias acs='apt-cache search'
    alias acsh='apt-cache show'
    alias sdi='sudo dpkg -i'
    alias neogeo='gngeo -H --scale=2 -e hq2x'
    alias neighbour='shell-fm lastfm://user/simplyw00x/neighbours'

    (the last two are a little frivolous )

  5. #5
    Join Date
    May 2006
    Beans
    50

    Re: Handy command-line aliases and tricks

    they all work great, except ls

    no matter what i do, ls is always the same - i want to add the -F

    i upgraded to dapper from breezy and as far as i can recall, i always had colors for file types.

    so i'm wondering if there's a universal setting that .alias can't take priority over or something?

  6. #6
    Join Date
    Jun 2006
    Location
    Gwangju, Korea
    Beans
    3,479

    Arrow Re: Handy command-line aliases and tricks

    Quote Originally Posted by evilhomer View Post
    they all work great, except ls

    no matter what i do, ls is always the same - i want to add the -F

    i upgraded to dapper from breezy and as far as i can recall, i always had colors for file types.

    so i'm wondering if there's a universal setting that .alias can't take priority over or something?
    Have you tried alias ls='ls -F'? enter it directly in the command line first to see if the alias works. Also, make sure that your .bashrc sources .alias (it needs to either contain a line with source .alias or . .alias

    Also, I would put the call to .alias at the bottom of your .bashrc

  7. #7
    Join Date
    May 2006
    Beans
    50

    Re: Handy command-line aliases and tricks

    ah, you showed me where to go! the alias from the command line worked, then i went to move .alias in .bashrc and in scrolling down, i saw .bashrc has the ls alias hardcoded into it.

    thanks!

  8. #8
    Join Date
    Oct 2005
    Beans
    20

    Re: Handy command-line aliases and tricks

    Code:
    ~% alias
    ...=../..
    ....=../../..
    .....=../../../..
    ......=../../../../..
    .......=../../../../../..
    :e=vim
    e=vim
    grep='grep --color=auto'
    k=killall
    l=less
    la='ls -A'
    ll='ls -l'
    ls='ls --color=auto'
    n=nautilus
    p=popd
    q=exit
    run-help=man
    t=cat
    vi=vim
    which-command=whence
    I'm not sure where run-help and which-command came from, but the others are mine. Of course, some are more useful under other shells than bash... =)

    ~d

  9. #9
    Join Date
    Jul 2006
    Beans
    23

    Re: Handy command-line aliases and tricks

    do you have to do anything to get your aliases activated, i read to put my aliases in my .bash_profile. but i have restarted my computer and everything and they dont seem to work.

    this is what i have right now

    Code:
    # ~/.bash_profile: executed by bash(1) for login shells.
    # see /usr/share/doc/bash/examples/startup-files for examples.
    # the files are located in the bash-doc package.
    
    # the default umask is set in /etc/login.defs
    #umask 022
    
    # include .bashrc if it exists
    if [ -f ~/.bashrc ]; then
        . ~/.bashrc
    fi
    
    # set PATH so it includes user's private bin if it exists
    if [ -d ~/bin ] ; then
        PATH=~/bin:"${PATH}"
    fi
    
    alias today='date +"%A, %B %-d, %Y"'
    
    alias l='ls -l'
    thanks

  10. #10
    Join Date
    Jun 2006
    Location
    Gwangju, Korea
    Beans
    3,479

    Re: Handy command-line aliases and tricks

    Put the aliases in ~/.bashrc, not ~/.bash_profile. .bash_profile only gets read by login shells (e.g., at the console or via ssh). All shells, however, read .bashrc.

    EDIT: You don't have to restart your computer. Type exit and restart the shell, and if your aliases are in the right place, they will be available.

Page 1 of 6 123 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •