Skip to content
Snippets Groups Projects
bash-2-the-basics.md 12.6 KiB
Newer Older
jacques.dainat_ird.fr's avatar
jacques.dainat_ird.fr committed
# Bash

Shells offer many possibilites:


 * **Built-in** commands that useful predefined programs.
 * **Command pipes** enable users to direct the output of one program to be the input for another program.
 * **System variables** can be set at the command line.
 * **History** feature that enable the user to recall previous commands issued.
 * **Scripting** for running user programs from the command line.

![](../images/2-basics/timeline_shell.png){: style="height:250px"}

The Bourne Shell (sh) has been written by Stephen Bourne and released in 1977.  
`Bash` born in 1989 is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. `Bash` stand for **b**orn **a**gain **sh**ell.


**Why using Bash?**

![](../images/2-basics/bash.png){: style="height:250px" align=right}

Bash is often preferred over other shells for many reasons:

  - its widespread availability
  - its compatibility with various shell features
  - its rich scripting capabilities
  - its large supportive community
  - default shell on many systems. 
  
  However, the choice of a shell ultimately depends on personal preference and specific use cases.

!!! tip
    On Mac the default shell before 2003 was `tcsh`, that has been replaced by `bash` from macOS Panther. Since 2019 with macOS Catalina the default shell is now `zsh`.

!!! exercise
    Open your terminal, and check what is your shell.
    The command you type is: `echo $SHELL`

## Some basics before starting important 

* If a line is longer that the windows, the rest of the line is written in the next line
* No way to move the cursor with the mouse.

![](../images/2-basics/long_line.png){: style="height:50px;"}

* Each time you press enter, bash will try to interpret the text as a command
* There is an history! You can move back to previous commands by pressing the ↑ key on your keybord. You can move down with ↓.


!!! Exercise
    * copy past this text in your terminal:
    ```
    hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hellllllllllllllllllllllllooooooooooooooooooooooooo
    ```
    What happens?
    ??? example "Click to show the solution"
        The line is executed as a command, and bash return the following message: `-bash: hello: command not found`

    * Write the same command (but avoid bash to interpret it)  
    Where is your cursor now?
    ??? example "Click to show the solution"
        * press ↑
        * You should see the last command entered in the terminal with the cursor at the end of the line

    * Move your cursor to the beginning of the line.
    
    ??? example "Click to show the solution"
        * press ← as many time as needed. It moves character by character.
        * press Option/Alt key + ←. It moves word by word.
        * press Ctrl + a. It moves directly to the beginning of the line.

## The Unix directory structure 

**/ – The root directory**

Everything, all the files and directories, in Linux are located under `root` represented by `/`. If you look at the directory structure, you’ll realize that it is similar to a plant’s root.

![](../images/2-basics/linux-directory-structure.jpg)

What you have to remember:

  
  * ** `/home` contains user personal data **  
    If your name is `tux` **your** home will be under `/home/tux`
    `~` is a special character that represent your home
  * `/usr` contains user binaries and program data
  * never run `rm -rf /` !!!! Whit that command you ask your system to forcefully and recursively delete the contents of the root directory.

## Commands

What is that? (try in your terminal).
```bash
pwd
```

??? example "Click to show the solution"
    A command. The `pwd` command prints (the full path) of current/working directory.
    pwd is an acronyme of `Print Working Directory`

What is that? (try in your terminal).
```bash
hello
```

??? example "Click to show the solution"
    This is not a command and bash let you know.
    You should get the following message: `-bash: hello: command not found`

What is that? (try in your terminal).
```bash
ls
```

??? example "Click to show the solution"
    A command. The `ls` command lists contents of a directory.

What is that (the second element)? (try in your terminal).
```bash
ls -l
```

??? example "Click to show the solution"
    A command with an option. The `-l` is an option meaning `long format`.


What is that (the second element)? (try in your terminal).
```bash
echo hello
```

??? example "Click to show the solution"
    A command with an argument.


Let's well decipher difference between option and argument:

```bash
command [ -option ] [ arguments ]
```

  * [ ] means this is optional (e.g. `ls` vs `ls -l`)
  * **Option** only modify the behavior of the command. It starts with `-` (or `--` for long option)
  * **Argument** controls the output of the command. It specifies a target for the command.

Try now the following command:

```bash
ls -l /
```

!!! question 
    What is the option and what is the argument in this command?  
    What this command does?

??? example "Click to show the solution"
    `-l` is the option and `/` the argument.  
    The command lists in long format what is contained at the root of your computer (The root directory).

Here the few first command good to know:

| Command | action |
| :-: | :-: |
| ls | Inspect files and directories |
| pwd | Print working directory |
| echo | Print a value e.g: `echo "coucou"` |

How can I know what a command is doing and what are the available options?

??? example "Click to show the solution"
    * Internet is your friend. A good place to keep in mind is ([http://ss64.com/mac](http://ss64.com/mac) or [http://ss64.com/bash](http://ss64.com/bash))
    * Have a lazy dog (have a look at the `cheat sheet` tab on top of this page )
    * Use **man**, **help** or **info** command e.g.: `man ls`

Try this command in your terminal:

```bash
man pwd
```

Let's end this section by learning how to execute several commands in a simple way.
Please execute these two commands:

```bash
echo below the output of the ls command:
```

```bash
ls
```

You will probably get an output looking similar as the picture below.

![](../images/2-basics/cmd1.png)

!!! question "Do you see any peculiarity?"
    ??? example "Click to show the solution"
        Indeed the `prompt` is printed  before each command.

It is possible to execute several commands in one line using `;`in between commands. Try the following:

```bash
echo below the output of the ls command: ; ls
```

You should get an output looking looking similar as the picture below

![](../images/2-basics/cmd2.png)

!!! question "Do you see any peculiarity?"
    ??? example "Click to show the solution"
        In fact, the two commands are now executed one after the other, without the user being prompted between the two commands.

A last detail to keep in mind: All shell commands are synchronous! the shell waits for the command to complete before it executes the next one.

## Variables

### User variables 

Let's discover the variables.  First we need to think about few things...  

!!! question "what is that?"

```
v
```
??? example "Click to show the solution"
    Indeed it is not a command, if you run it in the terminal you get `-bash: v: command not found` but this is not the point here. 
    It might be a variable but we do not know what is it yet...
    `v` is just a **character** often abreviated **char**.

!!! question "And what is that?"

```
var
```
??? example "Click to show the solution"
    Indeed it is not a command neither, if you run it in the terminal you get `-bash: var: command not found` but this is not the point here. 
    It might be a variable but we do not know what is it yet...
    `var` is just a **String** for now.

But then, what is a variable then?

**A variable is a named storage location that holds a value or information. Think of a variable as a container. The name of the variable allows you to refer to and access the stored value.**

In bash any character or string can become a variable storing any value using the `=` sign as follow:

```bash
v=hello
var=4
```

Try in your terminal.
!!! question "What happens?"
??? example "Click to show the solution"
    Right, nothing actually happens, bash understand that you created variables named `v` and `var` that hold values. That's it.

To display what is hold by a variable we must use the command `echo`.  
Let's try to display the value stored within the `var` variable.

```bash
echo var
```
!!! question "What happens ?"
    
??? example "Click to show the solution"
  Actually not so much, `echo` command will just display the *string* `var`. Bash does not know that you wanted to use `var` as a **variable** and not as a **string**.

Now try 

```bash
echo $var
```
Much better isn't it?

!!! tip
    You may enconter `$var` and `${var}` syntaxes in the Bash world. The second is prefered by developpers because may avoid some surprises in complex commands.

### System variables 

Bash has variables set by default.  
If you want to see the list of those default variables type the `env` command.

#### The SHELL variable

Let's take the `SHELL` variable to play with. 

!!! question "How to display specificaly the value hold by the `SHELL` variable?"
    
??? example "Click to show the solution"
    ```bash 
    echo $SHELL 
    ```

Actually this variable is very important because it tells which shell you are using in the terminal.  
If you whish to list shells available on your computer run:

```bash
cat /etc/shells
```

!!! tip
    If you need to change your shell by default when openin a terminal e.g. `sh`, run the following command:

    ```
    chsh -s /bin/sh
    ```

    You'll have to enter your user account's password. Then any new terminal windows shoud run with the new shell. 

!!! warning
    Commands may be different depending the `shell` you use. Be sure to use `Bash`for this course.  
    For each `shell` (as for any tool) it may exists different versions. To check the `Bash` version you are using use the following command:
    ```bash
    bash --version
    ```

## History

At any time you can access the historic of the command you ran in your terminal.
Try the command:

```bash
history
```
You should get something an output like this one


![](../images/2-basics/history.png){: style="height:50px;"}

where the value on the left is the entry number. By default Bash history save the 2000 last entries. The behaviour can be tuned. The history is in memory and related to your terminal. If you have several terminals open, thre is one history per terminal. When you close the a terminal, the history of the session will be appended to the end of the `.bash_history` file in your home directory.

You can execute a command of your bash history using `!` and the line number. e.g.:

```bash
!831
```
will execute the `echo $var` command.  


## Clear

If your screen gets too cluttered, you can clear your terminal using the `clear`` command. You can still access previous commands using ↑ and ↓ to move line-by-line, or by scrolling in your terminal.

```bash
clear
```

jacques.dainat_ird.fr's avatar
jacques.dainat_ird.fr committed
## Command Autocompletion

It exist a wonderful behavior in Bash called the autocompletion. What it is? 
Autocompletion refers to a feature that allows you to automatically complete the names of **commands** and file paths by pressing the Tab key. This feature can significantly improve efficiency and reduce the need to type out long or complex names manually.

When you start typing a command and press the Tab key ↹, Bash will attempt to complete the command name based on the available commands.

If there is only one possible completion, it will be filled in automatically. If there are multiple possibilities, Bash will list them, and you can continue typing or press Tab again to cycle through the options.

!!! exercise 
    Let's try with the `history` command. Start by typing `his` and press the Tab key ↹.  
    What happens?
    ??? example "Click to show the solution"
        Bash will automatically fill `history`
    But is that the only command starting by history? Try to press the Tab key ↹ again.
    ??? example "Click to show the solution"
        Apparently yes, it is the only one, othewise a list of command starting by `history` would have poped up this time.   

jacques.dainat_ird.fr's avatar
jacques.dainat_ird.fr committed
!!! Success "Quick recap"
    In this section we've learned a lot of things:

    - What is bash
    - What is a command and how to launch one
    - How to execute two commands using the `;` separator
    - A bunch of useful commands (`pwd`,`echo`,`ls`, etc)
    - How to find help for a command (`man`)
    - The Unix directory structure
    - How to set bash as shell (in case it is not your default shell)
    - The existence of an history
    - How to clear your terminal
jacques.dainat_ird.fr's avatar
jacques.dainat_ird.fr committed
    - Autocompletion