🏡 Blamechance's Digital Cottage

Search

Search IconIcon to open search

Bash Basic Syntax

Last updated Feb 24, 2024 Edit Source

# Learning Resources:

Skimming and pulling creating notes for TILs:


# Hello World Scripting

What is the line that all bash scripts need to start with, and why? ? A shebang (`#!) declaration is required, so that the system knows what program/shell needs to be used in the running of the script.

1
#! /bin/bash

To check version on debian/ubuntu/pop:

1
lsb_release -a

What permission change is required of bash script files to allow it’s functionality? Explain the octal permission system and the common argument for sharing a script. ? Bash scripts need to have it’s permission set to executable for the relevant principal executing. A common note, is to use chmod 755 to only allow others read and execute permissions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Octal base permissions:

0 = None  
1 = Execute  
2 = Write  
4 = Read

The rest are simply combinations of the base octals:

3 is 1 + 2       // Execute and Write  
5 is 1 + 4       // Execute and Read  
6 is 2 + 4       // Write and Read  
7 is 1 + 2 + 4   // Execute, Write, Readtip: if the number is odd, it includes Execute

# Variables and Conditional Arguments

What syntax is used to receive user input to a variable? ? read e.g

1
2
3
4
5
6
7
echo First name?
read FIRST_NAME

echo Last name?
read LAST_NAME

echo Hello $FIRST_NAME $LAST_NAME

What are positional arguments and what is the 0-th position reserved for? ?

What is the syntax to make use of positional arguments? ? echo $1 $2 etc.

1
2
3
#! /bin/bash

echo Hello $1 $2

# Output Redirection

How do you redirect script output? ? Redirects are done using “>”.

What is the difference between CTRL + d and CTRL + c in interacting with terminal? ?

What syntax allows appending text to an existing file, instead of overwriting it? ?

1
cat B.txt >> A+B.txt

# Input Redirection

What is a heredocs, what is it commonly used with and Why? ?

What is syntax for use of Heredocs? ?

1
2
3
4
5
# The script will process everything between the delimiters (in this case EOF), as input to the command. 
cat << EOF
The current working directory is: $PWD
You are logged in as: $(whoami)
EOF
1
2
The current working directory is: /home/linuxize
You are logged in as: linuxize
1
2
3
4
5
6
7
8
9
tommy@tommy-ubuntu-pc:~/Desktop$ sort -d << EOF
> C
> B
> A
> EOF
# output: 
A
B
C

What does <<< syntax denote? ?

1
wc -w <<< "Hello there wordcount!" 
1
2
# output: 
3

What are the different syntax methods to provide input to a command? ?

# Comments

What is the syntax for comments in bash? ?

1
2
3
4
5
6
7
8
# Comments can be like this

: ' 
or even
like
this
for blocks of text
'

# Piping

What is piping? What is it’s syntax? ? Piping is the practice of feeding the output of one command, into another.

1
ls -l /bin/bin | grep bash

This will only show ls results will hence only show results that contain the string “bash”.

# Test Operators

What syntax refers to the exit code of the last command executed? How would you print this to terminal? ?

What is syntax to incorporate test/evaluation operators to a command? ?

# Conditionals and Test Expressions (if/elif/else)

How would you syntactically write an if comparison statement for a bash script, referencing the first provided argument to the command? ? Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/bash

if [ ${1,,} = herbert ]; then 
	echo "asserted Herbert!"
elif [ ${1,,} = help ]; then
	echo "Enter your username!" 
else
       echo "Don't recognise user!"
fi

# note: the commas simply denote to lowercase the variable through variable expansion. 

# the following showss

What is the equivalent to len(x) in bash? ?

How do you close if statements in bash? ? fi.

What is the syntax for case statements, noting start, end and new statement syntax. ?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/bash

case ${1,,} in
	herbert | administrator)
		echo "Hello, you're the boss here!"
		;;
	help)
		echo "Just enter your username!"
		;;
	*)
		echo "Hello there. You're not the boss of me. Enter a valid username!"
esac

# Arrays

How do you declare arrays in bash? ? MY_FIRST_ARRAY=("Apple" "Orange" "Banana")

How would you index into the first item in a bash array? How would you print the WHOLE array? ?

How do you add items to arrays in bash? What happens when you ?

How do you remove items from arrays in bash? ? You use the unset command.

1
2

unset fruits[2]  # Deletes the element at index 2 (orange)

Does bash support slicing? ? Yes - for example, you can get a range of elements using ${array[start_index:end_index]}:

1
some_fruits=("${fruits[@]:1:3}")  # Copies elements from index 1 to 3

# Bash Functions

What is bash syntax for defining and calling a function? ? Definition:

1
2
3
4
# Define a function named "greet"
greet() {
    echo "Hello, welcome to Bash functions!"
}

Example script calling function:

1
2
3
4
5
6
7
#!/bin/bash

hello_world() {
   echo 'hello, world'
}

hello_world

How can you pass arguments within script and from terminal, to functions? ?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash

# Define a function that uses $1 (local argument)
local_function() {
    local local_arg="$1"
    echo "Local argument: $local_arg"
}

# Call the local_function
local_function "LocalArgValue"

# Use $1 (script argument)
echo "Argument from terminal: $1"

---
input:
./example.sh TerminalArgValue

output: 
Local argument: LocalArgValue
Argument from terminal: TerminalArgValue

# Parameter and expansion

The hash symbol # and the percent signs `

  1. ${variable#pattern}

    • When you use ${variable#pattern}, it removes the shortest match of pattern from the beginning of the value stored in variable.
  2. `${variable

    • When you use `${variable

Here’s a brief example to illustrate further:

1
2
3
4
text="Hello, World!" 

echo ${text#Hello,}  # Outputs: " World!" 
echo ${text%World!}  # Outputs: "Hello, "

# Compressing a folder:

1
tar -czvf archive_name.tar.gz directory_name