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]
Get the total number of elements in an array
${#fruits[*]}
Shell expansion
A mechanism to calculate arithmetical operations, to save results of command’s executions, …
Brace expansions
Allow us to generate:
- Arbitrary strings
echo beg{i,a,u}n # begin began begun - Ranges
echo {0..5} # 0 1 2 3 4 5
echo {00..8..2} # 00 02 04 06 08
Command substitution
Allows us to evaluate a command and substitute its value into another command or variable assignment.
It is performed when a command is enclosed by `` or $():
now=date +%T
or
now=$(date +%T)
echo now # 15:45:03
Arithmetic expansion
The expression that performs an arithmetic operation must be enclosed by $(( ))
result=$(( ((10 + 5*3) - 7) / 2 ))
echo result # 9
Create a folder structure where src, dest, and test folders each have index.js and util.js files
mkdir -p project/{dest,src,test}
touch project/{dest,src,test}/{index,util}.js
What does mkdir’s -p flag do?
Makes parent directories, as needed.
mkdir -p project/{dist,src,test}
project would be a parent directory
Streams in Bash
Sequences of characters Bash can receive input, and send output as.
Redirection in Bash
Redirection controls where the output of a command can go, and where the input of a command can come from.
These operators are used for redirecting streams:
> redirect output &> redirect output and error output &>> append redirected output and error output < redirect input << here documents <<< here strings
# output of ls will be written to list.txt ls -l > list.txt
# append output to list.txt ls -a >> list.txt
# all errors will be written to errors.txt grep da * 2> errors.txt
# read from errors.txt less < errors.txt
Pipes in Bash
Let us use output of a program as the input of another.
command1 | command2 | command3
command1 sends its output to command2, which then passes it on to the input of command3.
Constructions like this are called pipelines.
This can be used to process data through several programs.
ls -l | grep .md$ | less
The output of ls is sent to the grep programme, which prints only files with a .md extension, and this output is finally passed to the less programme.
List of commands in Bash
A sequence of one or more pipelines separated by one of the following operators:
; execute sequentially, one after another. the shell waits for the finish of each command
& if a command is terminated by &, it is executed asynchronously in a subshell (background)
&& right command will be executed only if its preceding command finishes successfully
|| right command will be executed only if its preceding command finishes unsuccessfully.
Conditionals in Bash
if [[]]; then elif[[]]; then else fi
if [[ `uname` == "Adam" ]]; then echo "Do not eat an apple!" elif [[ `uname` == "Eva" ]]; then echo "Do not take an apple!" else echo "Apples are delicious!" fi
Conditionals for working with file system in Bash
[[ -e FILE ]] - if file exists
[[ -f FILE ]] - if file exists and is a file
[[ -d FILE ]] - if file exists and is a direcorry
[[ -s FILE ]] - if file exists and is not empty
[[ -r FILE ]] - if file exists and is readable
[[ -w FILE ]] - if file exists and is writable
[[ -x FILE ]] - if file exists and is executable
[[ -L FILE ]] - if file exists and is symbol
[[ FILE1 -nt FILE2 ]] - if FILE1 is newer than FILE2
[[ FILE1 -ot FILE2]] - if FILE1 is older than FILE2
Conditionals for working with strings
[[ -z STR ]] - string is empty
[[ -n STR ]] - string is not empty
[[ STR1 == STR2 ]] - are equal
[[ STR1 != STR2 ]] - are not equal
Arithmetic operators in Bash
= -eq
!= -ne
< -lt
> -gt
<= -le
> = -ge
Combining expressions in Bash
Conditions may be combined using combining expressions
[[ ! EXPR ]] if EXPR is fals
[[ (EXPR) ]] returns the value of EXPR
[[ EXPR1 -a EXPR2 ]] - logical end
[[ EXPR1 -o EXPR2 ]] - logical or
Case statements in Bash
case "$FRUIT" in (apple) echo 'I like them' ;; (banana) echo 'It is ok" ;; (orange|tangerine) echo 'i do not like' && exit 1 ;; (*) echo 'unknown fruit' ;; esac
Kinds of loops in Bash
- for
- while
- until
- select
For loop in Bash
for arg in elem1 elem2 ... elemN do # statements done
as a one liner (there needs to me a ; before do):
for i in {1..5}; do echo $i; done
C-like style:
for (( i = 0; i < 10; i++ )); do
echo $i
done
When are for loops useful in Bash
!/bin/bash
When we want to perform the same operation over each file in a directory. E.g. to move all .sh files into the script folder and give them executable permissions.
for FILE in $HOME/*.sh; do
mv “$FILE” “${HOME}/scripts”
chmod +x “${HOME}/scripts/${FILE}”
done
While loop in Bash (squares of nums from 0-9)
!/bin/bash
x = 0 while [[ $x -lt 10 ]]; do echo $(( $x * $x )) x = `expr $x + 1` done
Until loop
until [[ condition ]]; do #statements done
Loop control
prints all odd numbers from 0 - 9
There are the break and continue statements for situations where we need to:
- stop a loop before its normal ending or
- step over an iteration
for (( i = 0; i < 10; i++ )); do
if [[ $(($i % 2)) == 0 ]]; then continue; fi
echo $i
done
Function in Bash
A sequence of commands grouped under a single name.
Calling a function is like calling any program, you just write the name and the function will be invoked.
Declaring a function: my_func () { # statements }
my_func # call my_func
Functions can take arguments and return a result - exit code
greeting () { if [[ -n $1 ]]; then echo "Hello, $1!" else echo "Hello, unknown!" fi return 0 }
greeting World # Hello, World!
greeting # Hello, unknown
Exit status codes in Bash
0 - success
1 - failure
Local variables in Bash functions
Declared using the local keyword, accessible only within a single function’s scope.
local local_var=”I’m a local variable”
How can you make your own commands in terminal
Define functions in your ~/.bashrc file
Define command aliases
alias ll=’ls -alF’
in ~/.bashrc
Change a variable’s value in Bash
x=0
x = expr $x + 1
Run scripts in debug mode
!/bin/bash -x
- Use an option in a script’s shebang
- Use the set command to debug just a part of a script. Options are turned on/off using -/+
echo "xtrace is turned off" set -x echo "xtrace is enabled" set +x echo xtrace is turned off again
Debugging options in Bash
- f (noglob) disable filename expansion (globbing)
- i (interactive) script runs in interactive mode
- n (noexec) read commands, but don’t execute them (syntax check)
- t exit after first command
- v (verbose) print each command to stdout before executing it
- x (xtrace) print each command before executing it and expands commands
Move files in Shell
mv - takes two arguments, the source and the destination
mv old new # renames old to new
mv file subdir/file # moves file to subdir file
mv file* subdir # moves all matched to ‘name*’ files to the ‘subdir’