Differences between revisions 1 and 169 (spanning 168 versions)
Revision 1 as of 2007-05-21 23:13:29
Size: 10534
Editor: Lhunath
Comment: Initial document.
Revision 169 as of 2015-04-10 20:29:39
Size: 8312
Editor: GreyCat
Comment: shortened PDF guide link
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
= Guide to BASH Operation and Scripting = #acl GreyCat:read,write,revert,admin,delete Lhunath:read,write,revert pgas:read,write,revert All:read
[[BashGuide/CommandsAndArguments|Commands and Arguments ->]]
----
= Introduction =

'''You are invited to make additions or modifications so long as you can keep them accurate. Please test any code samples you write.'''
Line 5: Line 10:
["BASH"] is a BourneShell compatible shell, which adds many new features to its ancestor. Most of them are available in the KornShell, too. If a question is not strictly shell specific, but rather related to Unix, it may be in the UnixFaq. --------
<<Anchor(About)>>
= About This Guide =
Line 7: Line 14:
[[TableOfContents]] A [[http://guide.bash.academy/|new version of this guide]] is currently being drafted. For now, this guide is still the most complete and best reviewed. Any contributions to the new guide are welcome [[https://github.com/lhunath/bash.academy|via GitHub forks]].
Line 9: Line 16:
This guide aims to aid people interested in learning to work with [[BASH]]. It aspires to teach good practice techniques for using BASH, and writing simple scripts.
Line 10: Line 18:
== Introduction == This guide is targeted at beginning users. It assumes no advanced knowledge -- just the ability to login to a Unix-like system and open a command-line (terminal) interface. It will help if you know how to use a text editor; we will not be covering editors, nor do we endorse any particular editor choice. Familiarity with the fundamental Unix tool set, or with other programming languages or programming concepts, is not required, but those who have such knowledge may understand some of the examples more quickly.
Line 12: Line 20:
This guide aims to become a point of reference for people interested in learning to work with ["BASH"]. It aspires to teach its readers good practice techniques in developing scripts for the ["BASH"] interpreter and educate them about the internal operation of ["BASH"].

This guide is targetted at beginning users. It assumes no basic knowledge, but rather expects you to have enough common sense to put two and two together. If something is unclear to you, you should report this so that it may be clearified in this document for future readers.
If something is unclear to you, you are invited to report this (use BashGuideFeedback, or the `#bash` channel on `irc.freenode.org`) so that it may be clarified in this document for future readers.
Line 18: Line 24:
The primary maintainer(s) of this document:
Line 19: Line 26:
== A Definition ==  * -- [[Lhunath]] (primary author)
 * -- GreyCat
Line 21: Line 29:
["BASH"] is an acronym for '''''B'''ourne '''A'''gain '''SH'''ell''. It is based on the ''Bourne'' shell and is mostly compatible with its features. The guide is also available in [[http://s.ntnu.no/bashguide.pdf|PDF format]].
Alternatively, you can just hit print after going to [[FullBashGuide]]. That guarantees you'll be printing the latest version of this document.
Line 23: Line 32:
Shells are applications that provide users with the ability to interact with their operating system on an interactive level, or to allow them to execute batch processes quickly. In no way are they required for execution of processes, they are merely a layer between system function calls and the user. --------
<<Anchor(Definition)>>
= A Definition =

BASH is an acronym for '''''B'''ourne '''A'''gain '''Sh'''ell''. It is based on the ''Bourne'' shell and is mostly compatible with its features.

Shells are command interpreters. They are applications that provide users with the ability to give commands to their operating system interactively, or to execute batches of commands quickly. In no way are they required for the execution of programs; they are merely a layer between system function calls and the user.

Think of a shell as a way for you to speak to your system. Your system doesn't need it for most of its work, but it is an excellent interface between you and what your system can offer. It allows you to perform basic math, run basic tests and execute applications. More importantly, it allows you to combine these operations and connect applications to each other to perform complex and automated tasks.

BASH is '''not''' your operating system. It is not your window manager. It is not your terminal (but it oftens runs ''inside'' your terminal). It does not control your mouse or keyboard. It does not configure your system, activate your screensaver, or open your files when you double-click them. It is generally not involved in launching applications from your window manager or desktop environment. It's important to understand that BASH is only an interface for you to execute statements (using BASH syntax), either at the interactive BASH prompt or via BASH scripts.
Line 26: Line 45:
== Using ["BASH"] == --------
 . '''In The Manual: [[http://www.gnu.org/software/bash/manual/bashref.html#Introduction|Introduction]]'''
----
 . ''Shell'': A (possibly interactive) command interpreter, acting as a layer between the user and the system. <<BR>> ''Bash'': The Bourne Again Shell, a ''Bourne'' compatible shell.
Line 28: Line 50:
Most users that think of ["BASH"] think of it as a prompt and a commandline. That is ["BASH"] in ''interactive mode''. ["BASH"] can also run in ''non-interactive mode'' through scripts. We can use scripts to automate certain logic. Scripts are basically lists of commands that you can type on the commandline. When such a script is executed, all these commands are executed sequentially; one after another. --------
<<Anchor(Using_Bash)>>
= Using Bash =
Line 30: Line 54:
We'll start with the basics in an ''interactive shell''. Once you're familiar with those, you can put them together in scripts. Most users that think of BASH think of it as a prompt and a command line. That is BASH in ''interactive mode''. BASH can also run in ''non-interactive mode'', as when executing scripts. We can use scripts to automate certain logic. Scripts are basically lists of commands (just like the ones you can type on the command line), but stored in a file. When a script is executed, all these commands are (generally) executed sequentially, one after another.
Line 32: Line 56:
We'll start with the basics in an ''interactive shell''. Once you're familiar with those, you can put them together in scripts.
Line 33: Line 58:
== The Basics ==

BASH takes commands on the commandline. Commands can be different things. They can be application executables, aliasses, function names, etc.

  * '''Application Executables''': ["BASH"] keeps a variable that tells it where to find the executables for certain applications. This variable is called `PATH`, and it usually contains `/bin:/usr/bin`. This is a string of pathnames separated by colons. Each path can contain executables. When a command is specified in ["BASH"] without a pathname (e.g. `ls`), ["BASH"] searches these paths for the executable for this command.
  * '''Aliasses''': ["BASH"] can use aliasses to make it easier to quickly execute complex commands. An alias is a ''name'' that is mapped to a certain ''string''. Whenever that ''name'' is used as a command in bash, it is replaced by the ''string''.
  * '''Functions''': Functions in ["BASH"] are much like aliasses. When a command is executed by the name of a function, the code of that function is executed instead.

Each command can be followed by arguments. It is very important that you understand how this works exactly. If you don't grasp these concepts well, the quality of your code will degrade significantly and you will introduce very dangerous bugs. So, pay close attention in the next few chapters.
'''Important! <<BR>> You should make yourself familiar with the `man` and `apropos` commands on the shell. They will be vital to your self-tutoring.'''
Line 44: Line 61:
    $ ls
    a b c
$ man man
$ man apropos
Line 48: Line 65:
`ls` is a command that lists files in the current directory. In this guide, the `$` at the beginning of a line represents your BASH prompt. Traditionally, a shell prompt either ends with `$`, `%` or `#`. If it ends with `$`, this indicates a shell that's compatible with the Bourne shell (such as a POSIX shell, or a Korn shell, or Bash). If it ends with `%`, this indicates a ''C shell'' (csh or tcsh); this guide does not cover C shell. If it ends with `#`, this indicates that the shell is running as the system's superuser account (`root`), and that you should be extra careful.

Your actual BASH prompt will probably be much longer than `$`. Prompts are often highly individualized.

The `man` command stands for "manual"; it opens documentation (so-called "man pages") on various topics. You use it by running the command `man [topic]` at the BASH prompt, where `[topic]` is the name of the "page" you wish to read. Note that many of these "pages" are considerably longer than one printed page; nevertheless, the name persists. Each command (application) on your system is likely to have a man page. There are pages for other things too, such as system calls or specific configuration files. In this guide, we will only be covering commands.

Note that if you're looking for information on BASH built-ins (commands provided by BASH, not by external applications) you should look in `man bash` instead. BASH's manual is extensive and detailed. It is an excellent reference, albeit more technical than this guide.

Bash also offers a `help` command which contains brief summaries of its built-in commands (which we'll discuss in depth later on).
Line 51: Line 76:
    $ mkdir d
    $ cd d
    $ ls
$ help
$ help read
Line 56: Line 80:
`mkdir` is a command that creates a new directory. We specified the argument `d` to that command. This way, the application `mkdir` is instructed to create a directory called `d`. After that, we use the application `cd` to change the current directory to `d`. `ls` shows us that the current directory (which is now `d`) is empty, since it doesn't display any filenames. --------
 . '''In the FAQ: <<BR>> [[BashFAQ/061|Is there a list of which features were added to specific releases (versions) of Bash?]]'''
----
 . ''Interactive mode'': A mode of operation where a prompt asks you for one command at a time.
 . ''Script'': A file that contains a sequence of commands to execute one after the other.
--------
Line 58: Line 87:
= Contents =
Line 59: Line 89:
== Commandline Argument Splitting == The guide has been divided into sections, which are intended to be read roughly in the order presented. If you skip ahead to a specific section, you might find yourself missing some background information from previous sections. (Links to relevant sections are not always provided when a topic is mentioned.)
Line 61: Line 91:
Commands in ["BASH"] can take multiple arguments. These arguments are used to tell the command exactly what it's supposed to do. In ["BASH"], you separate these arguments by whitespace (spaces, tabs and newlines).  * [[/CommandsAndArguments|Commands and Arguments]]
  * Types of commands; argument splitting; writing scripts.
 * [[/SpecialCharacters|Special Characters]]
 * [[/Parameters|Parameters]]
  * Variables; special parameters; parameter types; parameter expansion.
 * [[/Patterns|Patterns]]
  * Globs; filename matching; extended globs; brace expansion; regular expressions.
 * [[/TestsAndConditionals|Tests and Conditionals]]
  * Exit status; {{{&&}}} and {{{||}}}; if, test and {{{[[}}}; while, until and for; case and select.
 * [[/Arrays|Arrays]]
  * Arrays; associative arrays.
 * [[/InputAndOutput|Input and Output]]
  * Redirection; here documents; here strings; pipes; process substitution.
 * [[/CompoundCommands|Compound Commands]]
  * Subshells; command grouping; arithmetic evaluation; functions; aliases.
 * [[/Sourcing|Sourcing]]
  * Reading commands from other files.
 * [[/JobControl|Job Control]]
 * [[/Practices|Practices]]
  * Choosing your shell; quoting; readability; debugging.
Line 63: Line 112:
{{{
    $ ls
    $ touch a b c
    $ ls
    a b c
}}}

`touch` is an application that changes the 'Last Accessed'-time of a certain file to the current time. If the filename that it's given does not exist yet, it simply creates that file, as a new and empty file. In this example, we passed three arguments. `touch` creates a file for each argument. `ls` shows us that three files have been created.

{{{
    $ rm *
    $ ls
    $ touch a b c
    $ ls
    a b c
}}}

`rm` is an application that removes all the files that it was given. ''*'' is a ''glob''. It basically means ''all files in the current directory''. You will read more about this later on.

Now, did you notice that there are several spaces between `a` and `b`, and only one between `b` and `c`? Also, notice that the files that were created by `touch` are no different than the first time. You now know that the amount of whitespace between arguments does not matter. This is important to know. For example:

{{{
    $ echo This is a test.
    This is a test.
    $ echo This is a test.
    This is a test.
}}}

In this case, we provide the `echo` command with four arguments. 'This', 'is', 'a' and 'test.'. `echo` takes these arguments, and prints them out one by one with a space inbetween. In the second case, the exact same thing happens. The extra spaces make no difference. To protect the whitespace properly, we need to pass the sentence as one single argument. We can do this by using quotes:

{{{
    $ echo "This is a test."
    This is a test.
}}}

Quotes group everything together and pass it as a single argument. This argument is 'This is a test.', properly spaced. `echo` prints this single argument out just like it always does.

Be very careful to avoid the following:

{{{
    $ ls
    The secret voice in your head.mp3 secret
    $ rm The secret voice in your head.mp3
    rm: cannot remove `The': No such file or directory
    rm: cannot remove `voice': No such file or directory
    rm: cannot remove `in': No such file or directory
    rm: cannot remove `your': No such file or directory
    rm: cannot remove `head.mp3': No such file or directory
    $ ls
    The secret voice in your head.mp3
}}}

You need to make sure you quote filenames properly. If you don't you'll end up deleting the wrong things! `rm` takes filenames as arguments. If you do not quote filenames with spaces, `rm` things that each argument is another file. Since ["BASH"] splits your arguments at the spaces, `rm` will try to remove each word.

Please have a good look at http://bash-hackers.org/wiki/doku.php?id=syntax:words if all this isn't very clear to you yet.


== Globs ==

Globs are a very important concept in ["BASH"], if only for their increadible convenience. Properly understanding globs will benefit you in many ways. Globs are basically patterns that can be used to match filenames or other strings.

Globs are composed of normal characters and meta characters. Meta characters are characters that have a special meaning. These are the basic meta characters:

  * '''*''': Matches any string, including the null string.
  * '''?''': Matches any single character.
  * '''[...]''': Matches any one of the enclosed characters.

Here's an example of how we can use glob patterns to expand to filenames:

{{{
    $ ls
    a abc b c
    $ echo *
    a abc b c
    $ echo a*
    a abc
}}}

["BASH"] sees the glob, for example 'a*'. It `expands` this glob, by looking in the current directory and matching it against all files there. Any filenames that match the glob, are enumerated and replaced by the glob. As a result, the statement `echo a*` is replaced by the statement `echo a abc`, and is then executed.

BASH will always make sure that whitespace and special characters are escaped properly when expanding the glob. For example:

{{{
    $ touch "a b.txt"
    $ ls
    a b.txt
    $ rm *
    $ ls
}}}

Here, `rm *` is expanded into `rm a\ b.txt`. This makes sure that the string `a b.txt` is passed as a single argument to rm, since it represents a single file. It is important to understand that using globs to enumerate files is nearly '''always''' a better idea than using `ls for that purpose. Here's an example with some more complex syntax which we will cover later on, but it will illustrate the problem very well:

{{{
    $ ls
    a b.txt
    $ for file in `ls`; do rm "$file"; done
    rm: cannot remove `a': No such file or directory
    rm: cannot remove `b.txt': No such file or directory
    $ for file in *; do rm "$file"; done
    $ ls
}}}

Here we use the `for` command to go through the output of the `ls` command. The `ls` command results in a string `a b.txt`. The `for` command splits that string into arguments over which it iterates. As a result, for iterates over `a` and `b.txt`. Naturally, this is '''not''' what we want. The glob however expands in the proper form. It results in the string `a\ b.txt`, which `for` takes as a single argument.

["BASH"] also supports a feature called `Extended Globs`. These globs are more powerful in nature. This feature is turned off by default, but can be turned on with the `shopt` command, which is used to toggle '''sh'''ell '''opt'''ions:

{{{
    $ shopt -s extglob
}}}

  * '''?(list)''': Matches zero or one occurrence of the given patterns.
  * '''*(list)''': Matches zero or more occurrences of the given patterns.
  * '''+(list)''': Matches one or more occurrences of the given patterns.
  * '''@(list)''': Matches one of the given patterns.
  * '''!(list)''': Matches anything except one of the given patterns.

The list inside the paranthesis is a list of globs separated by the `|` character. Here's an example:

{{{
    $ ls
    names.txt tokyo.jpg california.bmp
    $ echo !(*jpg|*bmp)
    names.txt
}}}

Our glob now expands to anything that does not match the `*jpg` or the `*bmp` pattern. Only the text file passes for that, so it is expanded.
----
[[BashGuide/CommandsAndArguments|Commands and Arguments ->]]
----
CategoryShell

Commands and Arguments ->


Introduction

You are invited to make additions or modifications so long as you can keep them accurate. Please test any code samples you write.

All the information here is presented without any warranty or guarantee of accuracy. Use it at your own risk. When in doubt, please consult the man pages or the GNU info pages as the authoritative references.


About This Guide

A new version of this guide is currently being drafted. For now, this guide is still the most complete and best reviewed. Any contributions to the new guide are welcome via GitHub forks.

This guide aims to aid people interested in learning to work with BASH. It aspires to teach good practice techniques for using BASH, and writing simple scripts.

This guide is targeted at beginning users. It assumes no advanced knowledge -- just the ability to login to a Unix-like system and open a command-line (terminal) interface. It will help if you know how to use a text editor; we will not be covering editors, nor do we endorse any particular editor choice. Familiarity with the fundamental Unix tool set, or with other programming languages or programming concepts, is not required, but those who have such knowledge may understand some of the examples more quickly.

If something is unclear to you, you are invited to report this (use BashGuideFeedback, or the #bash channel on irc.freenode.org) so that it may be clarified in this document for future readers.

You are invited to contribute to the development of this document by extending it or correcting invalid or incomplete information.

The primary maintainer(s) of this document:

The guide is also available in PDF format. Alternatively, you can just hit print after going to FullBashGuide. That guarantees you'll be printing the latest version of this document.


A Definition

BASH is an acronym for Bourne Again Shell. It is based on the Bourne shell and is mostly compatible with its features.

Shells are command interpreters. They are applications that provide users with the ability to give commands to their operating system interactively, or to execute batches of commands quickly. In no way are they required for the execution of programs; they are merely a layer between system function calls and the user.

Think of a shell as a way for you to speak to your system. Your system doesn't need it for most of its work, but it is an excellent interface between you and what your system can offer. It allows you to perform basic math, run basic tests and execute applications. More importantly, it allows you to combine these operations and connect applications to each other to perform complex and automated tasks.

BASH is not your operating system. It is not your window manager. It is not your terminal (but it oftens runs inside your terminal). It does not control your mouse or keyboard. It does not configure your system, activate your screensaver, or open your files when you double-click them. It is generally not involved in launching applications from your window manager or desktop environment. It's important to understand that BASH is only an interface for you to execute statements (using BASH syntax), either at the interactive BASH prompt or via BASH scripts.



  • Shell: A (possibly interactive) command interpreter, acting as a layer between the user and the system.
    Bash: The Bourne Again Shell, a Bourne compatible shell.


Using Bash

Most users that think of BASH think of it as a prompt and a command line. That is BASH in interactive mode. BASH can also run in non-interactive mode, as when executing scripts. We can use scripts to automate certain logic. Scripts are basically lists of commands (just like the ones you can type on the command line), but stored in a file. When a script is executed, all these commands are (generally) executed sequentially, one after another.

We'll start with the basics in an interactive shell. Once you're familiar with those, you can put them together in scripts.

Important!
You should make yourself familiar with the man and apropos commands on the shell. They will be vital to your self-tutoring.

$ man man
$ man apropos

In this guide, the $ at the beginning of a line represents your BASH prompt. Traditionally, a shell prompt either ends with $, % or #. If it ends with $, this indicates a shell that's compatible with the Bourne shell (such as a POSIX shell, or a Korn shell, or Bash). If it ends with %, this indicates a C shell (csh or tcsh); this guide does not cover C shell. If it ends with #, this indicates that the shell is running as the system's superuser account (root), and that you should be extra careful.

Your actual BASH prompt will probably be much longer than $. Prompts are often highly individualized.

The man command stands for "manual"; it opens documentation (so-called "man pages") on various topics. You use it by running the command man [topic] at the BASH prompt, where [topic] is the name of the "page" you wish to read. Note that many of these "pages" are considerably longer than one printed page; nevertheless, the name persists. Each command (application) on your system is likely to have a man page. There are pages for other things too, such as system calls or specific configuration files. In this guide, we will only be covering commands.

Note that if you're looking for information on BASH built-ins (commands provided by BASH, not by external applications) you should look in man bash instead. BASH's manual is extensive and detailed. It is an excellent reference, albeit more technical than this guide.

Bash also offers a help command which contains brief summaries of its built-in commands (which we'll discuss in depth later on).

$ help
$ help read



  • Interactive mode: A mode of operation where a prompt asks you for one command at a time.

  • Script: A file that contains a sequence of commands to execute one after the other.


Contents

The guide has been divided into sections, which are intended to be read roughly in the order presented. If you skip ahead to a specific section, you might find yourself missing some background information from previous sections. (Links to relevant sections are not always provided when a topic is mentioned.)


Commands and Arguments ->


CategoryShell

BashGuide (last edited 2015-04-10 20:29:39 by GreyCat)