Skip to content

alanngo/ShellScripts

Repository files navigation

Bash Shell


Basic

  • BE CAREFUL W/ SPACES
  • we want to automate linux commands
  • know the following commands by heart
    • echo
    • pwd
    • ls
    • cd
    • cat
    • read
    • alias
    • git commands
  • how to run a shell script
$ ./<SCRIPT_NAME>.sh # use this for running shell scripts from working directory
$ sh <SCRIPT_NAME>.sh # use this for running shell scripts from different directory
$ bash <SCRIPT_NAME>.sh # running a script using bash command 
$ zsh <SCRIPT_NAME>.sh # running a script using zsh command 

Comments

# this is a comment
# don't catch you slippin now

Variables

Excplicit Declaration

VAR="sanjna" # declaring a variable explicitly
echo $VAR # referencing a declared variable

Numerical values

declare -i X=43 # declaring an int variable
echo $X # treat '43' as a string
echo $(( X )) # treat '43' as a number
Operator Functionality Example
+ addition $(( X + Y ))
- subtraction $(( X - Y ))
* multiplication $(( X * Y ))
/ division $(( X / Y ))
% modulus $(( X % Y ))

User Input

read VAR # takes user input from keyboard
echo $VAR # referencing a declared variable

Positional Command Line Argument

echo $1 # prints first arg
echo $2 # prints second arg
...
echo ${10} # prints the 10th argument 
echo ${20} # prints the 20th argument
# arguments after 9th must be enclosed in {}

Iterate thru Command Line Argument

for ARG in "$*"
do
    echo $ARG
done

Optional-Value Variables

  • replaces empty checks
  • much cleaner way to deal with optional variables
YOUTUBER=${1:-"Linus Tech Tips"} # if first arg is not present, default to Linus Tech Tips

Environment Variables

  • system/program info stored in variables
  • you can figure out their values by using the command below
$ echo $<ENV_VARIABLE> # replace <ENV_VARIABLE> w/ a variable from below
  • Useful commands when working w/ environment variables
$ env  # The command lists all of the environment variables in the shell.
$ printenv # The command prints all environment variables.
$ set # The command assigns or defines an environment variable.
$ unset # The command deletes the environment variable. 
$ export # The command exports the value of the newly assigned environment variable.
  • list of common linux environment variables
USER # The current logged in user.
HOME #The home directory of the current user.
EDITOR # The default file editor to be used i.e: vim, nano, emacs, ect... 
SHELL # The path of the current user’s shell, such as bash or zsh.
LOGNAME # The name of the current user.
PATH # A list of directories to be searched when executing commands. 
LANG # The current locales settings.
TERM # The current terminal emulation.
MAIL # Location of where the current user’s mail is stored.

Conditionals

  • SPACES MATTER in between brackets and expression
  • 4 kinds
    • if
    • else
    • elif
    • case
  • comparison operators
Operator Functionality Example
== two strings are equal $VAR1 == $VAR2
!= two strings are NOT equal $VAR1 != $VAR2
< less than for strings $VAR1 < $VAR2
> greater than for strings $VAR1 > $VAR2
-n string length > 0 -n $VAR1
-z string length == 0 -z $VAR1
-eq two numbers are equal $num1 -eq $num2
-ne two numbers are NOT equal $num1 -ne $num2
-lt less than for numbers $num1 -lt $num2
-le less than or equals for numbers $num1 -le $num2
-gt greater than for numbers $num1 -gt $num2
-ge greater than or equals for numbers $num1 -ge $num2

if, else, elif, else

if [ expression ]; then # need a space between brackets 
   ...
elif [ expression ]; then
    ...
else
    ...
fi # DO NOT FORGET THE FINISH CLAUSE!

case

case $VAR in
    pattern1)
    ...
    ;; # don't forget the terminating statements
    pattern2)
    ...
    ;;
    pattern3)
    ...
    ;;
    *) # default case
    echo "default case "
esac # finish clause for case

Loops

  • while
  • for
  • until
# standard while loop
while [ condition ]; do  # spaces matter between brackets
    ...
done # don't forget the done clause
# infinite while loop
while :  # ':' will always evaluate to true
do 
    ...
done # don't forget the done clause
# for loop
for var in v0 v1 v2 ... vN; do  # set of words
    ...
done # don't forget the done clause
# until loop
until [ condition ]; do
    ...
done # don't forget the done clause

Arrays

  • they are dynamically sized
  • they are loosely typed
  • zero-based indexed
ARRAY=(1 2 3 4 5) # declaring an array

This is how to print arrays

# print the whole array
echo ${ARRAY[@]}
echo ${ARRAY[*]}
# * and @ means all
# print the array in a certain range
echo ${ARRAY[@]:1} # gives us 2 3 4 5
echo ${ARRAY[*]:1:3} # gives us 2 3 
# ${ARRAY[*]:<START>:<COUNT_ELEMENT>} => array from index <START> and count 
# the number of elements specified by <COUNT_ELEMENT>
# if no count is specified, it will be from <START> to end of array
# using for loop
for e in "${ARRAY[*]}; do
    echo $e
done

How to access array properties

# print an array at a certain index
echo ${ARRAY[2]} # gives us 3

# print the size of an array
echo ${#ARRAY[*]} # gives us 5

Functions

  • can take 0 or multiple arguments
  • called differently than other programming languages
  • use these for large-scale automation

Defining and calling a function method 1

foo() # defining foo
{
    ... # do stuff
}

foo # calling foo DO NOT USE ()

Defining and calling a function method 2 USE THIS METHOD

function foo() # defining foo by using 'function keyword'
{
    ... # do stuff
}

foo # calling foo DO NOT USE ()

Defining and calling a function with arguments

function foo()
{
    # use the 'local' keyword to declare variables in the functions scope
    local A1=$1
    local A2=$2
    ...
}

foo # calling foo DO NOT USE ()

Returning a value from a function

function foo() # defining foo by using 'function keyword'
{
    return 123
}

foo # calling foo DO NOT USE ()

Show git branch in terminal

append this into ~/.bashrc

# Show git branch name
force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages