Saturday, April 25, 2009

Command Line Tricks


I have seen a lot of people who are new to Linux who are aware of the poor scripting tools and command line tools that Windows has; these same people bring the same attitudes to Linux.
Command Line Tricks

The default shell under Linux, bash (the Bourne Again Shell, an old UNIX joke), has a number of very useful facilities.


command and file name completion.

You do not have to slavishly type in the whole of a command's name or the whole of a file's name if it is an argument to a command. bash can complete these things for you if what you have already typed in is unambiguous.

Try for example: mor

That is hit the tab key after tying in 'mor'

Under most circumstances, bash will complete it to 'more ' for you, and wait for you to type in a file name.

Next, try: mo

In this case, nothing happens, except that bash may beep at you. Here, what you have typed is ambiguous, so bash can't complete it.

To see what commands are available, hit the tab key twice in succession. bash will display all the possibilities, and you can usually enter one or two more characters and hit tab again, and bash will complete the command for you.

The same is true for file names as arguments.

bash is a veritable programming language that has variables, programming statements and so forth.

The DOS command prompt is crap by comparison.

Let us say that you are downloading a file, something that many of us do frequently, I think. You want to do something else after the download is finished, and you want to watch it in a window while you do other things in other windows.

Instead of manually entering an 'ls -al ' in a window every now and then, here is an approach that will automatically show you how far the download has got every minute.

while [ 1 ]
ls -al ; sleep 60

What this does is loop forever (while [ 1 ] says while true do etc)

Then do an 'ls -al' of the file. You will have to specify the file name and path. Then the semicolon allows me to put two commands on the one line.

Then we sleep for 60 seconds, and then complete the loop.

Try it with other commands. You can use it with

ps -ax | grep

to check that a process is still running and so on ...

When you are finished, use ^C (That is control-C) to kill the loop.

Then recall the command (with the up-arrow key) and see what bash has recorded it as. See all those extra semicolons there? That is how you enter the above loop all on the one line ...

Of course, if you want to get a file and then do something after, you could use wget to get the file and simply enter another command after a semicolon of something like that.

Next posting, someone will explain STDIN, STDOUT, and STDERR, along with talking about what is going on with piping commands together. Then we will get to bash variables, and more complex loops.

No comments: