Code 3: Bash Basics

Learning Bash from scratch
coding
linux
bash
Author

Tony Phung

Published

February 28, 2024

1. Basics

echo $SHELL: The shell?
vim shelltest.sh: Open shelltest.sh in Vim
#! /bin/bash: Place in front of bash script to tell Linux which Shell to run
ls -l: long format list
chmod u+x shelltest.sh: user to have executable rights on shell.sh man wc + arrows + q: manual of word-count script
wc --help: quick reference of word-count script ${1,,}: Parameter Expansion - Ignores lower and upper-cases when comparing to values

2. Variables

FIRST_NAME=tony: set a variable
echo FIRST_NAME: echo the variable’
\': escape the single quote with backtick

2.1 Fixed Variables

hellothere.sh # [Terminal]
#!/bin/bash
FIRST_NAME=Tony
LAST_NAME=JustDevs
echo Hello $FIRST_NAME $LAST_NAME
cbmod u+x hellothere.sh # [Terminal]
./hellothere.sh # [Terminal]

2.2 Interactive Variables

hellothere_interactive.sh # [Terminal]
#/bin/bash

echo What is your first name?
read FIRST_NAME
echo What is your last name?
read LAST_NAME

echo Hello $FIRST_NAME $LAST_NAME
cbmod u+x hellothere_interactive.sh # [Terminal]
./hellothere_interactive.sh # [Terminal]

2.3 Positional Arguments

vim hellothere_posarg.sh  # [Terminal]
#!/bin/bash

echo Hello $1 $2
cbmod u+x hellothere_posargs.sh     # [Terminal]
./hellothere_posargs.sh Tony JustDevs # [Terminal]

3. Output redirection

3.1 Piping |

  • The output of the previous command ls -l /usr/bin is forwarded to the command after the |.
  • Add grep bash to filter for bash.
ls -l /usr/bin | grep bash # [Terminal]

3.2 Override >

E.g. Logging something from a script to a log-file: 1. Catch output from echo command
2. Override of a text file

echo Hello World! > output_override_to_text.txt
cat output_override_to_text.txt

3.3 Append >>

Append from script to a log-file: 1. Catch output from echo command
2. Append output into a text file

echo Hello World! > output_append_to_text.txt
cat output_override_to_text.txt
echo Good day matey! > output_append_to_text.txt
cat output_override_to_text.txt

4. Input direction

  1. <: from a file
  2. <<: from multiple lines of text
  3. <<<: from single string of text

4.1 < from a line

Use word-count wc command to for number of words in text 1. Command to receive Input 2. Input direction of text

wc -w < output_append_to_text.txt # input direction
cat output_append_to_text.txt | wc -w # output direction

4.2 << from multiple lines

Supply multiple lines of words 1. Command to receive Input 2. Input direction to Command 3. KeywordStart 4. Actual text 5. KeywordEnd

cat << EOF
this is some text
with multiple
lines
EOF

4.3 <<< from single line

wc -w <<< "a sentence line with 6 words"

5. Test Operators

5.1 Equality

Tests whether an express exists with 0(No issues) or 1 (Error) 1. Write expression 2. Print exit-code of last executed command

[ hello = hello ]
echo $? # exits 0

[ 1 = 0 ] 
echo $? # exits 1

[ 1 -eq 1 ] # equate numericals
echo $?

5.2 If / Elif / Else

${1,,} Parameter Expansion: Ignores lower and upper-cases when comparing to values

#/bin/bash

if [ ${1,,} = tonydevs ]; then
        echo "Oh, you're the boss here. Welcome!"
elif [ ${1,,} = help]; then
        echo "Just enter your username, duh!"
else
        echo "I don't know who you are. But you're not the boss of me!"
fi
~       

5.3 Case statements

Better than if / elif /else: - Checking for multiple values - is easier to read

vim case_stmts.sh #[Terminal]
#!/bin/bash

case ${1,,} in
        tony | administrator)
                echo "Gday, 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
https://www.youtube.com/watch?v=tK9Oc6AEnR4

6. Arrays

Store multiple variables in a list called Arrays

6.1 Indexing

MY_FIRST_LIST=(one two three four five)
echo $MY_FIRST_LIST # print only first element [TERMINAL]
echo ${MY_FIRST_LIST[@]} # prints everything
echo ${MY_FIRST_LIST[1]} # prints second element

6.2 Indexing

item: each element in loop
${MY_FIRST_LIST[@]}: all items in list
do echo -n: do echo and ignore all new line characters
$item: represents each single item in array
|: output direction
wc -c: count characters
done: finish loop

for item in ${MY_FIRST_LIST[@]}; do echo -n $item | wc -c; done

7. Functions

7.1 Function only

  1. Create shell
  2. Define function
  3. Catch output for up and since with their different flags
  4. Print everything between the two EOFs keywords
  5. Call the variables generated
  6. Close function
vim first_function.sh # [Terminal]
#!/bin/bash 
showuptime(){
    up=$(uptime -p | cut -c4-)
    since=$(uptime -s)
    cat << EOF
------
This machine has been up for ${up}
It has been running since ${since}
------
EOF
}
showuptime

7.2 Not Declaring Local Variables (Wrong!)

If variables inside a function are not declared local, they may override variables of the same name in the global variables in the global environment/

#!/bin/bash 
up="global up" # add global variable 1
since="global since" # add global variable 2 
echo $up
echo $since

showuptime(){
    up=$(uptime -p | cut -c4-)
    since=$(uptime -s)
    cat << EOF
------
This machine has been up for ${up}
It has been running since ${since}
------
EOF
}
showuptime
echo up is: $up
echo since is: $since

7.3 Declaring Local Variables in a Function

Define variables inside functions as local variables so they’re only available to the functions and not to the entire script.

#!/bin/bash 
up="global up" 
since="global since" 
echo $up
echo $since

showuptime(){
    local up=$(uptime -p | cut -c4-) # add local prefix to declare local variable 1
    local since=$(uptime -s) # add local prefix to declare local variable 2
    cat << EOF
------
This machine has been up for ${up}
It has been running since ${since}
------
EOF
}
showuptime
echo up is: $up
echo since is: $since

7.4 Position Arguments

Just like shell scripts, shell functions can also have positional arguments

#!/bin/bash

showname(){
    echo hello $1 $2
}
showname Tony JustDevs

8. Exit Codes

#!/bin/bash
showname(){
    echo hello $1
    if [ ${1,,} = tony ]; then
        return 0
    else
        return 1
    fi
}
showname() $1
if [ $? = 1 ]; then
    echo = "A strange has called the function!"
fi

9. awk

Filter contents to and fro: 1. files or 2. output of a command

9.1 Filter a Text File

echo one two three > onetwothree.txt #[Terminal]
awk '{print $1}' onetwothree.txt

9.2 Filter a CSV File

vim csv_test.csv 
one,two,three #[csv_test.csv]
awk -F, '{print $1 $2}'

9.3 Piping into awk

echo "Just get this world: Hello" | awk '{print $5}'
echo "Just get this world: Hello" | awk -F: '{print $2}' | cut -c2

10. sed

Replace values in text files with Regular Expressions

Example: sed 's/word1/word2/g' sedtest.txt

sed: replace values command
s: means subtsitute
g: globally, across the whole text file -i.ORIGINAL: keeps original file appends .ORIGINALto file name

# [terminal]
vim sed_test.txt

# [sed_test.txt]
The fly flies like no fly flies. 
A fly is an insect that has wings and a fly likes to eat leftovers  

# Just prints into terminal 
sed 's/fly/grasshopper/g' sedtest.txt 

# replace og file with command + creates new file .txt.ORIGINAL of og content
sed -i.ORIGINAL 's/fly/grasshopper/g' sedtest.txt