views:

78

answers:

5

i am novice to the Linux shell and had to recently start using it for work...i have now got used to the basic commands in bash to find my way around...however there are a lot of commands i find myself typing over and over again and its kind of a hassle to type them every time...so can anyone tell me how can i shorten the command syntax for ones i use frequently.

A very simple example, i use the ls -lh command often, though this is quite short but im just giving an example. Can I have something (a shell script may be) so that I can run it by typing just say lh.

I want to do it for more complex commands.

+5  A: 
alias lh='ls -lh'

If you want to make this persistent across sessions, put it in your .bashrc file. Don't forget to run source .bashrc afterwards to make bash aware of the changes.

If you want to pass variables, an alias just isn't enough. You can make a function. As an example, consider the command lsall to list everything in a given directory (note this is just an example and thus very error prone):

function lsall
{
    ls $1/*
}

$Ngets replaced with the Nth argument.

Job
after you edit your .bashrc, the changes won't magically appear in your current shell -- you will have to `source .bashrc`. New terminal windows will pick up the changes.
glenn jackman
@glenn jackman: Thanks, I updated my answer.
Job
+3  A: 

You would place the following alias in your .bashrc file:

alias lh='ls -lh'

Now lh is shorthand for ls -lh.

For more complicated tasks you could use a bash function. For example, on one of my machines I have a function which causes 'ls' to run after every successful 'cd':

cdls() {
  builtin cd "$*"
  RESULT=$?
  if [ $RESULT -eq 0 ]; then
    ls
  fi
}
alias cd='cdls'
John Ledbetter
+1  A: 

you can define aliases. For longer commands, use a function, put it into a library file and source it whenever you want to use your functions.

ghostdog74
And be sure and follow the link to functions as well - sometimes an alias is just too simple.
Paul Tomblin
+1  A: 

Just for the sake of completeness, since you want to learn bash: you could also write a function

lh() {
    ls -lh "$@"
}

although I would never write that when a simple alias would do ;-)

cadrian
+1  A: 

;) Heh, I remember one problem when I was starting out on Linux, which is that I would ask questions like these, and people would diligently answer them, but no one would explain how to make such changes permanent, and so I found myself typing in a bunch of commands every time I opened a terminal.

So, even though others have accurately answered this question... if you want to make the change permanent, put the alias-line into your ~/.profile or ~/.bashrc file (~ = your home directory). It depends a bit on your distribution on which is run when, but I always try adding my aliases to ~/.profile first and if that doesn't work, then ~/.bashrc. One of them should work for sure.

Helgi Hrafn Gunnarsson