Joey's Notes: Bash shell basics
By Joey Prestia
It is often said that the real power of Linux lies at the command line - and this is true. Unfortunately, many new Linux users start out trying Linux as a desktop operating system and get frustrated when they discover the frequent necessity of using the command line - an unfamiliar and thus uncomfortable environment. This usually happens when they need to install from a tarball (compileable source code in a tar.gz file) and discover that they have to type commands or navigate to a specific directory. To make matters worse, the directory-separator slash (/) is the wrong way if they're used to DOS.
Or perhaps they need to get video playback to work right - something that can still be quite challenging under Linux. These types of things can be quite difficult for new users because of numerous differences in the operating systems. My purpose here is to try to make the transition easier by explaining some basics that should help, whether you are trying to learn Linux formally or just starting out as a desktop user trying to break away from Microsoft.
In reality, Linux will become a whole lot easier if you get familiar with just a few key concepts. Among those things is the directory structure: for example, there's no more C:\ drive. Instead, Linux has the root of the file system located at '/', which is equivalent to C:\ in Windows. No matter how many drives there are in a Linux system, there will only be one filesystem tree - more drives just increase the available space. Linux does not use the concept of one directory tree for each drive like Windows does.
Learning the structure of this directory tree is one of the biggest hurdles for the new user. As an example, the part of the system containing your personal files is referred to as your home directory; its name is the same as your username, and it is located under the '/home' directory. There is a link to a great little tutorial at the end of this article that may take a couple of hours to go through, but it will definitely help you to get familiar with Linux.
Most commands in Linux are some short form of what the command does; e.g., the ls command stands for 'list', and cd being short for change directory. Just by learning a few simple commands you will be able to navigate your system effectively and perform many tasks, but be patient - it takes time. Linux has around 3000+ commands.
[ Actually, that statement is both true and misleading. Every program in Linux is a command, but you only need to know a tiny percentage of these to work on the command line effectively. In general, the standard Unix toolkit (e.g., this list of commands) is all that's necessary - and even experts are rarely completely familiar with all of these. In my opinion, knowing about 40 of these commands will suffice the average user 99.9% of the time. -- Ben ]
All of these have similarities in their syntax, and there are some basic concepts that are uniform across all commands. Perhaps the most important thing to remember is the man command; whenever you need to use some unfamiliar command, just type man command. This will pop up the manual page for that command, giving you information that you may need before you execute it.
The syntax of a command refers to the grammar of the sequence that we enter on the command line. To verify the syntax for a specific command, a quick glimpse at the appropriate man page will usually clear things up; this information is found under the SYNOPSIS heading. For most commands, the syntax is 'command options argument'.
- The name of a program like ls or cat or grep.
- A letter or a word preceded by a dash for "short options" or double dashes for the "long form" of an option. -a is a short option and --all is a long option; both mean the same thing.
- An argument may be a file name, a directory, a device specification like /dev/cdrom. It is usually tied to the option (e.g., '--file doc.txt') and is, in a sense, the object of the command.
Most people have problems deciding where to put a space in the command line. The best guideline is that there should be spaces after every command and between all options preceded by a minus. Arguments may or may not require preceding spaces. Again, the man page is often the best guide.
The first thing you'll see when working in the command shell is the shell prompt. Looking at it will normally tell you what user you are, your system hostname, and your location on the system.
[ This is not necessarily true on many other Unix systems, or even in some of the smaller Linux distros. Often, the prompt consists of nothing more than '$', '%', or '#' to show your user level and shell type; for more information, you may need to either configure the prompt or use some of the toolkit informational commands. -- Ben ]
Looking at the sample below, we can see that our username is 'tom'. This is followed by the @ symbol which separates the username from the system hostname; if you never named your system, it may have 'localhost' in this position. Following this, we have the '~' character which indicates that we are in this user's home directory. Finally, we have the '$' character; this tell us, in a general fashion, the level of permissions that we have as a user. This varies across different shells; for example, the C shells (csh, tcsh) will use '%' for a standard user, while the Bourne shell and its derivatives (sh, ksh, bash, zsh, and a number of others) will usually use '$'. The root user (the system's superuser) gets a special prompt of '#'; this lets the user know to be very, very cautious and precise in the commands they issue, since the root user can easily destroy or damage the system.
Typing the command echo $SHELL tom finds out he is using Bash (a.k.a., the "Bourne Again Shell".) The 'echo' command in this example prints the value of the $SHELL variable to the screen. The Bash shell is normally the default shell on most modern Linux systems.
[tom@station1 ~]$ echo $SHELL /bin/bash
If the current directory is not shown in the prompt, the first important command you should learn is pwd which is short for "print working directory". This will reveal the full path as we can see below.
[tom@station1 ~]$ pwd /home/tom
Commands are either shell built-ins, compiled executable programs, or executable scripts located somewhere on your system. The shell is a command interpreter which reads certain environment variables (you can see these by typing 'env' at the command line) when you open a command shell. When you type a command, the command interpreter will search the directories listed in the PATH variable to find the program you've asked it to execute. If it is not a shell built-in, an alias to a command, a defined function, or a program in the defined path, the command interpreter returns the 'command not found' error.
[tom@station1 ~]$ print help me bash: print: command not found
There are many commands - maybe too many. To see how many you have available, just hit the 'tab' key twice in a terminal; this will show you a number and ask if you actually want to see all of them. Don't worry: you'll never need to know most of them (many of these are invoked by other commands or via GUI menus.) No one can remember them all - there wouldn't be any point to it in the first place - and learning just a handful will help you out greatly on any Linux system.
Commands are case sensitive and are normally lower case. Another important thing to remember is that many commands (e.g., copying, moving, attaching a device, etc.) work in a "what to where" fashion:
cp /my/source/file /destination/file/or/directory mv /from/here /to/there mount /dev/mydevice /directory/to/mount/in
Switches and Options
Switches and options are used to modify the action of the command. They are usually preceded immediately by either a single or double dash, and are in the form of letters or full words. Some commands will require options and some will not. Here are some samples:
[tom@station1 ~]$ ls
Short option example:
[tom@station1 ~]$ ls -a
Multiple short options:
[tom@station1 ~]$ ls -a -h -i
Multiple short options can be grouped:
[tom@station1 ~]$ ls -ahi
Long option example:
[tom@station1 ~]$ ls --all
Multiple long options:
[tom@station1 ~]$ ls --all --human-readable --inode
Normally, short options can be grouped together if more than one is required. In addition, some short options have equivalent long options which perform the same action.
An argument is usually an object that the command operates on; whether a command takes an argument at all depends on the command. For example, the command ls can take an argument, but if none is supplied the command assumes the current working directory is the argument and lists the current directory. An example of a command that takes no arguments is 'true': it takes only options. Again, arguments vary depending on the command and a great many commands have a default argument.
Getting Help Using the Man Pages
When using the command line, it is advantageous to get in the habit of using Linux's built-in manual page system, also called the "man" pages. At first glance, the man pages can look intimidating and very cryptic. Be assured, though - they are very helpful and necessary. By using them you will greatly enhance the speed at which you are learning Linux. To see the man pages for a command, merely type 'man command' and a screen with information will pop up. To navigate a man page, you use the arrow keys and page-up/page-down keys to scroll, and the letter "q" to quit. There are a number of other navigation keys for searching, jumping to the top or the bottom, and so on; these depend on the pager program (usually 'more' or 'less', with the latter being most common.) You can read about these by hitting the 'h' key (help) while browsing the man page.
When you look at any man page, you will notice several section headings:
- The name of the command and often similar commands that may be of use.
- This section will give you the detailed syntax for running the command correctly. You may have to review the OPTIONS section, below, to get the precise details. There are many commands that must have options supplied to work at all.
- Usually a brief to detailed technical description of what the command does.
- Under this heading, there will be a listing of the long and short options that the command accepts. You will almost always need to use some sort of option with a command, so this section is quite important. This section can be fairly long. Since most commands use different meanings for their options, be aware that whatever options you used on one command may mean something completely different when used with some other command.
- When using unfamiliar commands I almost always look for this section so I don't foul something up. This section, if it exists, may further clarify up the syntax of the command being researched.
There may be more categories for some commands and less for others. This depends on the commands.
Learning Linux can be a long process but you will most definitely find it fun and rewarding as you discover the awesome power that it contains.
The Linux system was originally designed for the command line user, and if you know how to find the help that you need, you will have access to far more power than the average desktop user can even imagine. Another helpful source of information, if it is installed on your machine, is the 'info' command; this is the Texinfo documentation system, which contains the official documentation of the GNU Project. Some systems have both 'man' and 'info' available. It is a good idea to check both and see if one offers more information that is to your liking. Generally info pages tend to be easier to understand then the man pages, although in some instances the information is identical. To use the info system, type info command or just info to get familiar with it.
Another helpful feature of the Linux command line is tab command completion and path completion. If you are not sure of the correct complete spelling of a command or a file name you can just type a couple of the initial letters of that command and hit the 'tab' key to see what the Bash shell comes up with for assistance. If the command specified by what you've typed so far is unique, it will complete the task for you by filling in the spelling; if not, it will present you with a list of possible choices.
Assuming, for example, that you need a command that can help you configure your sound card but only remember that it starts with "syst". Just type
[tom@station1 ~]$ syst
Then hit tab (you may need to hit it twice depending on your configuration) which should reward you with the following output:
system-cdinstall-helper system-config-rootpassword system-config-authentication system-config-samba system-config-date system-config-securitylevel system-config-display system-config-securitylevel-tui system-config-kdump system-config-selinux system-config-keyboard system-config-services system-config-language system-config-soundcard system-config-lvm system-config-time system-config-network system-config-users system-config-network-cmd system-control-network system-config-packages system-install-packages system-config-printer systool
From this, you can see the name of the command you need: system-config-soundcard. This also works with paths to files. To use this feature and get the feel of how it works, start by typing a directory path - but after typing a couple of characters hit the tab key and see if it auto-completes for you. If it does not, it's because there is not enough characters to differentiate it from another possible choice. You can try adding another character or couple of characters and hitting the tab key again; this will allow it to complete for you. This can actually save you a lot of typing: 'cat /usr/include/c++/4.0.4/i486-linux-gnu/bits/messages_members.h' becomes 'cat /u⇒i⇒c+⇒⇒0.⇒i⇒b⇒m⇒' - 22 characters instead of 66!
Using the arrow keys also can make things easier. In Bash, these are mapped to what is called the command history: using the up arrow will take you to the previous executed command, and hitting the up arrow twice will take you back two commands. Of course, the down arrow does the opposite and moves you forward in the command history until no more commands are left. To see everything in the command history type history on the command line; recalling a previous command anywhere in the list can be done with 'Ctrl-R' and typing a part of that command. A command can also be recalled by noting its number in the 'history' output and typing an exclamation point followed by that number. There are many more shortcuts available; you can read about these in the 'HISTORY' section of 'man bash'.
Some basic commands and common switches
|pwd||Print working directory||--help||Display help information|
|man||Display manual page||[1-8]||Man page section number|
|-a||All relevant information|
|cd||Change directory||..||Up one level|
|/||Root of filesystem|
|~ or nothing||Current users home directory|
|ls||List files||-a --all||All even hidden files|
|-h --human-readable||Human readable sizes|
|cp||Copy files||-i --interactive||Prompt before overwrite|
|-r --recursive||Include underlying directories|
|-a --archive||Archive mode all files|
|mv||Move files||-i --interactive||prompt before overwrite|
|-u --update||move if file is newer|
|-f --force||Don't prompt before overwriting|
|rm||Remove files||-r --recursive||Include underlying directories|
|-f --force||Don't prompt before removal|
|-i --interactive||Prompt before removal|
|mkdir||Make directory||-p --parents||Make parent directories|
|-m --mode=MODE||Set file mode|
|-v --verbose||Print confirmation|
|rmdir||Remove directory||-p --parents||Remove directory and parents|
|-v --verbose||Print confirmation|
|--ignore-fail-on-non-empty||Ignore failure if files exist|
|cat||Concatenate files||-b --number-nonblank||Number the non blank lines|
|-n --number||Number all lines|
|-s --squeeze-blank||Only show one blank line|
|locate||Locate files||-c --count||Count matches instead|
|-i --ignore-case||Be case insensitive|
|-S --statistics||Locate database statistics|
|less||Show one page at a time||-N --LINE-NUMBERS||Print line numbers|
|-s --squeeze-blank-lines||Display only one blank line|
|-E --QUIT-AT-EOF||Make less stop at the last page|
|grep||Print lines matching a pattern||-i --ignore-case||Ignore case sensitivity|
|-R -r --recursive||Read all files under directory|
|-v --invert-match||Select non-matching lines|
|mount||Mount a device||-o||Specify additional options|
|-t||Manually specify file system type|
|-a||Mount all file systems in fstab|
|umount||Unmount a device||-t||Specify file system type|
|-r||On failure remount read olny|
Joey was born in Phoenix and started programming at the age fourteen on a Timex Sinclair 1000. He was driven by hopes he might be able to do something with this early model computer. He soon became proficient in the BASIC and Assembly programming languages. Joey became a programmer in 1990 and added COBOL, Fortran, and Pascal to his repertoire of programming languages. Since then has become obsessed with just about every aspect of computer science. He became enlightened and discovered RedHat Linux in 2002 when someone gave him RedHat version six. This started off a new passion centered around Linux. Currently Joey is completing his degree in Linux Networking and working on campus for the college's RedHat Academy in Arizona. He is also on the staff of the Linux Gazette as the Mirror Coordinator.