BASH Flashcards

1
Q

BASH

A

= Bourne Again Shell

A command processor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to grant a file the execute permission?

A

chmod +x filename

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

!

A

!/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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

sh / print to console

A

echo ‘Hello’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

BASH script

A

A list of shell commands written in a file.

Usually ends with the .sh extension

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

man ${command}

A

Get command’s manual

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Data types in Bash

A

Only strings and numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Types of variables in Bash

A
  1. Local variables
  2. Environment variables
  3. Variables as positional arguments
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Local variables in Bash

A

Exist only within a single script. Inaccessible to other programmes and scripts.

  • declare variable:
    foo=”value”
  • display value
    echo $foo
  • delete varible
    unset foo
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Using Bash variables in strings

A

Only possible within double quotes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Environment variables in Bash

A

Variables accessible outside of the current shell session, to other programmes, scripts, etc.

Defined like local variables, just preceded by ‘export’

export foo=’bar’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Most commonly used global variables in Bash

A

$HOME
$PWD
$USER
$RANDOM - random integer between 0 and 32767

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Positional parameters in Bash

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Default variables in Bash

A

Useful when you’re processing positional parameters which can be omitted

FOO=${FOO:-‘default’} or

echo “1: ${1:-‘one’}”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Assigning a variable the value of a command line output in Bash

A

It can be done by encapsulating the command with `` or $().

FILE_LIST=ls or
FILE_LIST=$(ls)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Array declaration in Bash

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

List all values in Bash array

A

${fruits[*]} or

${fruits[@]}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Bash array slice

A

Extracts the slice of the length 2 that starts at index 0.

${fruits[*]:0:2} #Apple Pear

${fruits[@]:0:2}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Bash slice of positional arguments

A

${@:1:2} or

${*:1:2}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Add elements to Bash array

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Delete elements from an array

A

unset fruits[0]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Get the total number of elements in an array

A

${#fruits[*]}

23
Q

Shell expansion

A

A mechanism to calculate arithmetical operations, to save results of command’s executions, …

24
Q

Brace expansions

A

Allow us to generate:

  1. Arbitrary strings
    echo beg{i,a,u}n # begin began begun
  2. Ranges
    echo {0..5} # 0 1 2 3 4 5
    echo {00..8..2} # 00 02 04 06 08
25
Q

Command substitution

A

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

26
Q

Arithmetic expansion

A

The expression that performs an arithmetic operation must be enclosed by $(( ))

result=$(( ((10 + 5*3) - 7) / 2 ))
echo result # 9

27
Q

Create a folder structure where src, dest, and test folders each have index.js and util.js files

A

mkdir -p project/{dest,src,test}

touch project/{dest,src,test}/{index,util}.js

28
Q

What does mkdir’s -p flag do?

A

Makes parent directories, as needed.

mkdir -p project/{dist,src,test}

project would be a parent directory

29
Q

Streams in Bash

A

Sequences of characters Bash can receive input, and send output as.

30
Q

Redirection in Bash

A

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
31
Q

Pipes in Bash

A

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.

32
Q

List of commands in Bash

A

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.

33
Q

Conditionals in Bash

A

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
34
Q

Conditionals for working with file system in Bash

A

[[ -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

35
Q

Conditionals for working with strings

A

[[ -z STR ]] - string is empty

[[ -n STR ]] - string is not empty

[[ STR1 == STR2 ]] - are equal

[[ STR1 != STR2 ]] - are not equal

36
Q

Arithmetic operators in Bash

A

= -eq

!= -ne

< -lt

> -gt

<= -le

> = -ge

37
Q

Combining expressions in Bash

A

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

38
Q

Case statements in Bash

A
case "$FRUIT" in
  (apple)
    echo 'I like them'
      ;;
  (banana)
    echo 'It is ok"
      ;;
  (orange|tangerine)
    echo 'i do not like' &amp;&amp; exit 1
      ;;
  (*)
    echo 'unknown fruit'
      ;;
esac
39
Q

Kinds of loops in Bash

A
  1. for
  2. while
  3. until
  4. select
40
Q

For loop in Bash

A
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

41
Q

When are for loops useful in Bash

A

!/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

42
Q

While loop in Bash (squares of nums from 0-9)

A

!/bin/bash

x = 0
while [[ $x -lt 10 ]]; do
  echo $(( $x * $x ))
  x = `expr $x + 1`
done
43
Q

Until loop

A
until [[ condition ]]; do
  #statements
done
44
Q

Loop control

A

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

45
Q

Function in Bash

A

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

46
Q

Exit status codes in Bash

A

0 - success

1 - failure

47
Q

Local variables in Bash functions

A

Declared using the local keyword, accessible only within a single function’s scope.

local local_var=”I’m a local variable”

48
Q

How can you make your own commands in terminal

A

Define functions in your ~/.bashrc file

49
Q

Define command aliases

A

alias ll=’ls -alF’

in ~/.bashrc

50
Q

Change a variable’s value in Bash

A

x=0

x = expr $x + 1

51
Q

Run scripts in debug mode

A

!/bin/bash -x

  1. Use an option in a script’s shebang
  1. 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
52
Q

Debugging options in Bash

A
  • 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
53
Q

Move files in Shell

A

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’