> For the complete documentation index, see [llms.txt](https://olb.gitbook.io/linux-essentials-certification/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://olb.gitbook.io/linux-essentials-certification/3.the-power-of-command-line/3.3-scripts.md).

# 3.3 Scripting

**Weight 4**\
Key knowledge areas

* Basic shell scripting
* Awareness of common text editors (vi and nano)

Partial list of the used files, terms and utilities

* \#! (shebang)
* /bin/bash
* Variables
* Arguments
* for loops
* echo
* Exit status

***

## Commands and path

* `which` : executable path
* `$PATH` : env. variable which contains directory where are commands
* `PATH=$PATH:mydirectory` add mydirectory to $PATH
* to execute a file there is 3 solutions:
  * move file to a directory listed in `$PATH`
  * add directory to `$PATH`
  * use `./filename`
* use `chmod +x` to add execute permission

## Defining the interpreter

* `#!/bin/bash` : shebang + path of interpreter

## Common text editors

### vi

* `H, J, K, L` keys to navigate
* `I` insert mode
* `Esc` navigation mode
* `:` command mode

### nano

* use `CTRL` + keys

## Variables

* `myvariable=toto` : create variable called 'myvariable' and assign value 'toto'
* `echo $myvariable` : output the value
* variables in bash are case sensitive, alphanumeric,considered implicitly as **STRING**

## Arguments

* `$1` : first script argument
* `$n` : n scripts arguments
* `$#` : number of arguments

## Conditional Logic

* If condition:
  * `if [ $myvariable -eq value ] then ... else ... fi`
  * `-ne` Not equal to (numerical comparaison)
  * `-gt` Greater than (numerical comparaison)
  * `-ge` Greater than or equal to (numerical comparaison)
  * `-lt` Less than (numerical comparaison)
  * `-le` Less than or equal to (numerical comparaison)
  * `==` Compare strings

## Exit Code

* `$?` : **0** if previous command execution is correct / **1 or other number** if previous command has failed

## Handle many arguments

* `$@` or `$*` : array of all the arguments

## For loop

* `for file in $FILES do echo "$file" done`
* `shift` remove first array element

## Regular Expression for Error checking

* `echo $1 | grep "^[A-Z]+$" > /dev/null if [ $? -ne 0 ] then echo "argument must start with a capital letter" fi`
