BASH Flashcards
BASH
= Bourne Again Shell
A command processor
How to grant a file the execute permission?
chmod +x filename
!
!/bin/bash
= sha-bang
The first line of a shell script file must begin with it.
It is followed by the full path to the shell interpreter:
or: #!/usr/bin/env bash
sh / print to console
echo ‘Hello’
BASH script
A list of shell commands written in a file.
Usually ends with the .sh extension
man ${command}
Get command’s manual
Data types in Bash
Only strings and numbers
Types of variables in Bash
- Local variables
- Environment variables
- Variables as positional arguments
Local variables in Bash
Exist only within a single script. Inaccessible to other programmes and scripts.
- declare variable:
foo=”value” - display value
echo $foo - delete varible
unset foo
Using Bash variables in strings
Only possible within double quotes.
Environment variables in Bash
Variables accessible outside of the current shell session, to other programmes, scripts, etc.
Defined like local variables, just preceded by ‘export’
export foo=’bar’
Most commonly used global variables in Bash
$HOME
$PWD
$USER
$RANDOM - random integer between 0 and 32767
Positional parameters in Bash
Variables allocated when a function is evaluated and they are given positionally.
Those are:
$0 - script’s name
$1..$9 - the parameter list elements from 1 to 9
${10-N} the parameter list elements from 10 to N
$* or $@ all positional parameters except $0
$# number of parameters, not counting $0
$FUNCNAME - the function name, has value only inside a function.
Default variables in Bash
Useful when you’re processing positional parameters which can be omitted
FOO=${FOO:-‘default’} or
echo “1: ${1:-‘one’}”
Assigning a variable the value of a command line output in Bash
It can be done by encapsulating the command with `` or $().
FILE_LIST=ls
or
FILE_LIST=$(ls)
Array declaration in Bash
You can assign a value to an index in the array variable:
fruits[0]=Apple
fruits[1]=Pear
fruits[2]=Plum
or use compound assignment:
fruits=(Apple Pear Plum)
List all values in Bash array
${fruits[*]} or
${fruits[@]}
Bash array slice
Extracts the slice of the length 2 that starts at index 0.
${fruits[*]:0:2} #Apple Pear
${fruits[@]:0:2}
Bash slice of positional arguments
${@:1:2} or
${*:1:2}
Add elements to Bash array
You use new compound array assignment to substitute the existing array in it, and then assign the new value to the original variable.
fruits=(Orange ${fruits[*]} Banana)
or you can assign a value to the next available index
fruits[3]=Banana
Delete elements from an array
unset fruits[0]