├── .gitignore ├── README.md ├── arithmetic.bash ├── array.sh ├── calendar.sh ├── case-statement.sh ├── celcius2fahrenheit.sh ├── convert-case.sh ├── elif-statement.sh ├── exercism ├── luhn.sh └── two-fer.sh ├── expansion.sh ├── file-expressions.sh ├── find-file.sh ├── ftp.sh ├── function.sh ├── giga2mega.sh ├── git-versions.sh ├── if-statement.sh ├── kjv.txt ├── leap-year.sh ├── loop.sh ├── nested-if-statement.sh ├── net-salary.sh ├── no-of-cpu.sh ├── ping-servers.sh ├── project.sh ├── pytest.py ├── special-bash-variables.sh ├── strings.sh ├── test-conditions.sh ├── test.sh ├── variables.sh └── word-count.sh /.gitignore: -------------------------------------------------------------------------------- 1 | test2.sh 2 | test3.sh 3 | test4.sh 4 | toptal 5 | exercism/test.sh 6 | testing.sh 7 | toptal_fibonachi.sh 8 | toptal_sum.sh 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bash-scripts 2 | 3 | Bash Scripts for Automation 4 | 5 | 1. no-of-cpu - Print the number of CPU cores using the **nproc** command 6 | -------------------------------------------------------------------------------- /arithmetic.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Addition and Subtraction 4 | fs1=$(du -b $1 | cut -f1) 5 | fs2=$(du -b $2 | cut -f1) 6 | 7 | echo "File size of $1 is: $fs1 bytes" 8 | echo "File size of $2 is: $fs2 bytes" 9 | 10 | total=$(($fs1+$fs2)) 11 | 12 | echo "Total size is: $total bytes" 13 | 14 | # Multiplication and Division 15 | echo $((5 / 2)) #truncates the decimal part 16 | echo "5/2" | bc -l #pass through the basic calculator to get the decimal portion 17 | 18 | echo "4.1 - 0.5" | bc -l 19 | -------------------------------------------------------------------------------- /array.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | files=("f1.txt" "f2.txt" "f3.txt" "f4.txt" "f5.txt") 4 | 5 | # print the elements of the array in reverse order 6 | echo ${files[4]} ${files[3]} ${files[2]} ${files[1]} ${files[0]} 7 | 8 | # print all the elements of the array 9 | echo ${files[*]} 10 | 11 | # print the total number of elements in the array 12 | echo ${#files[@]} 13 | 14 | # re-assing a value to an element 15 | files[0]="a.txt" 16 | echo ${files[*]} 17 | 18 | # add element to array (add f6.txt to files) 19 | files+=("f6.6xt") 20 | echo ${files[*]} 21 | 22 | # delete an element in the array (delete element in index 5) 23 | unset files[5] 24 | echo ${files[*]} 25 | 26 | # delete the entire array 27 | unset files 28 | echo "array deleted ${files[*]}" 29 | 30 | # get all the values of BASH_VERSINFO array 31 | ./extension.sh "${BASH_VERSINFO[*]}" 32 | # 3 2 57 1 release x86_64-apple-darwin21 33 | 34 | # get the length of element in the 5th index 35 | ./extension.sh "${BASH_VERSINFO[5]}" 36 | # :21: 37 | 38 | # get the 2nd and 3rd elements in BASH_VERSINFO array 39 | echo ${BASH_VERSINFO[@]:1:2} 40 | # 2 57 41 | 42 | # Holes in Indexed Array 43 | array=( a b c d e f g h i j ) 44 | unset array[2] array[4] array[6] array[8] 45 | ./extension.sh "${array[@]}" 46 | # :a: 47 | # :b: 48 | # :d: 49 | # :f: 50 | # :h: 51 | # :j: 52 | 53 | # With a sparse (or any) array, the ${!array[@]} expansion lists the subscripts: 54 | ./extension.sh "${!array[@]}" 55 | # :0: 56 | # :1: 57 | # :3: 58 | # :5: 59 | # :7: 60 | # :9: 61 | 62 | # to remove the holes 63 | array=( "${array[@]}" ) # converts associative array into an indexed array 64 | echo "${!array[@]}" 65 | # 0 1 2 3 4 5 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /calendar.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # script to print the calendar of an entire year 3 | echo -n "Please enter a year: " 4 | read year 5 | echo "Calendar of $year" 6 | cal $year 7 | -------------------------------------------------------------------------------- /case-statement.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Case Statement 3 | 4 | CHAR=$1 5 | 6 | case $CHAR in 7 | [a-z]) 8 | echo "Small Alphabet" ;; 9 | [A-Z]) 10 | echo "Big Alphabet" ;; 11 | [0-9]) 12 | echo "Number" ;; 13 | *) 14 | echo "Special Character" ;; 15 | esac 16 | 17 | -------------------------------------------------------------------------------- /celcius2fahrenheit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Convert Celcius to Fahrenheit 3 | # The value to be converted must be passed to the script as argument 4 | # The formula: F = C * (9/5) + 32 5 | C=$1 6 | F=$(echo "scale=2; $C * (9/5) + 32" | bc -l) #scale=2 keeps the resutl to 2 decimal places 7 | echo "$C degrees Celcius is equal to $F degrees Fahrenheit." 8 | -------------------------------------------------------------------------------- /convert-case.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # converts the contents of a file to uppercase 3 | # the file path must be passed to the script as argument 4 | 5 | echo "Displaying Content of $1 in upper case." 6 | cat $1 | tr [:lower:] [:upper:] -------------------------------------------------------------------------------- /elif-statement.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # elif statment 3 | 4 | AGE=$1 # age should be passed to script as an argument 5 | 6 | if [ $AGE -lt 13 ]; then 7 | echo "You are a kid" 8 | elif [ $AGE -lt 20 ]; then 9 | echo "You are a teenager" 10 | elif [ $AGE -lt 65 ]; then 11 | echo "You are an adult" 12 | else 13 | echo "You are an elder" 14 | fi -------------------------------------------------------------------------------- /exercism/luhn.sh: -------------------------------------------------------------------------------- 1 | # Given a number, determine wether or not it is vallid per luhn formula 2 | number="4539 3195 8343 6467" 3 | 4 | # trim/remove spaces in the string 5 | number="${number// }" 6 | length=$(echo -n $number | wc -c) # -n removes the trailing newline character 7 | echo $number 8 | echo $length 9 | 10 | for (( i=0; i<=length; 2i++ )); do 11 | echo ${number:i:i} 12 | done 13 | 14 | -------------------------------------------------------------------------------- /exercism/two-fer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Instructions 4 | # Two-fer or 2-fer is short for two for one. One for you and one for me. 5 | 6 | # Given a name, return a string with the message: 7 | 8 | # One for name, one for me. 9 | # Where "name" is the given name. 10 | 11 | # However, if the name is missing, return the string: 12 | 13 | # One for you, one for me. 14 | 15 | 16 | two_fer() { 17 | name="$1" 18 | echo "One for ${name:-you}, one for me" 19 | } 20 | 21 | two_fer "$@" 22 | -------------------------------------------------------------------------------- /expansion.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Expansion.sh file will be called with arugments 4 | # it will display what the shell has passed to it after processing 5 | # all the arguments. Each of its arguments is printed on a separate 6 | # line, preceded by the value of $pre and followed by the value of $post 7 | 8 | # The special parameter $@ expands to a list of all the command-line arguments, 9 | # but the results differ depending on whether it is quoted or not. When quoted, 10 | # it expands to the positional parameters "$1", "$2", "$3", "$4", and so on, and 11 | # the arguments containing whitespace will be preserved. If $@ is unquoted, 12 | # splitting will occur wherever there is whitespace. 13 | 14 | # expansion.sh script 15 | pre=: 16 | post=: 17 | printf "$pre%s$post\n" "$@" 18 | 19 | ############################ 20 | ##### Brace expansion ##### 21 | ########################### 22 | ./expansion.sh {one,two,three} 23 | # :one: 24 | # :two: 25 | # :three: 26 | 27 | ./expansion.sh {1..3} 28 | # :1: 29 | # :2: 30 | # :3: 31 | 32 | # A string before or after the brace expression will be included in each 33 | # expanded argument 34 | ./expansion.sh pre{d,l}ate 35 | # :predate: 36 | # :prelate: 37 | 38 | # Braces may be nested 39 | ./expansion.sh {{1..3},{a..c}} 40 | # :1: 41 | # :2: 42 | # :3: 43 | # :a: 44 | # :b: 45 | # :c: 46 | 47 | # Multiple braces within the same word are expanded recursively. 48 | # The first brace expression is expanded, and then each of the resulting words 49 | # is processed for the next brace expression. With the word {1..3} {a..c}, the 50 | # first term is expanded, giving the following: 51 | # 1{a..c} 2{a..c} 3{a..c} 52 | 53 | ./expansion.sh {{1..3}{a..c}} 54 | # :1a: 55 | # :1b: 56 | # :1c: 57 | # :2a: 58 | # :2b: 59 | # :2c: 60 | # :3a: 61 | # :3b: 62 | # :3c: 63 | 64 | # In version 4 of bash, numerical sequences can be padded with zeros, and the increment in a sequence 65 | # can be specified: 66 | ./expansion.sh {01..13..3} 67 | # :01: 68 | # :04: 69 | # :07: 70 | # :10: 71 | # :13: 72 | 73 | # Increments can also be used with alphabetic sequences: 74 | ./expansion.sh {a..h..3} 75 | # :a: 76 | # :d: 77 | # :g: 78 | 79 | 80 | ########################## 81 | #### Tilde Expansion #### 82 | ######################### 83 | 84 | # An unquoted tilde expands to the user’s home directory: 85 | ./expansion.sh ~ 86 | # :/Users/calistus: 87 | 88 | # Followed by a login name, it expands to that user’s home directory: 89 | ./expansion.sh ~root ~calistus 90 | # :/var/root: 91 | # :/Users/calistus: 92 | 93 | # When quoted, either on the command line or in a variable assignment, the 94 | # tilde is not expanded: 95 | ./expansion.sh "~" "~calistus" 96 | # :~: 97 | # :~calistus: 98 | 99 | # If the name following the tilde is not a valid login name, no expansion is 100 | # performed: 101 | ./expansion.sh ~ebunilo 102 | # :~ebunilo: 103 | 104 | #################################### 105 | ###### Process Substitution ######## 106 | #################################### 107 | # creates a temporary filename for a command or list of commands. You can use it 108 | # anywhere a file name is expected. The form <(command) makes the output of 109 | # command available as a file name; >(command) is a file name that can be written to 110 | 111 | ./expansion.sh <(ls -l) >(pr -Tn) 112 | # :/dev/fd/63: 113 | # :/dev/fd/62: 114 | 115 | ###################################### 116 | ######### Parsing Options ############ 117 | ##################################### 118 | 119 | progname=${0##*/} # get the name of the script without its path 120 | 121 | 122 | ###################################### 123 | ######## Parameter Expansion ######### 124 | ###################################### 125 | # ${var:-default} and ${var-default}: Use Default Values 126 | var= 127 | ./expansion.sh "${var:-default}" # if variable is unset or empty, it expands to a default string 128 | # :defualt: 129 | 130 | # if the colon is omitted, it checks only if it is unset 131 | var= 132 | ./expansion.sh "${var-default}" # the variable is set so it expands to nothing 133 | # :: 134 | 135 | unset var 136 | ./expansion.sh "${var-default}" # var is unset, so it expands to default 137 | # :default: 138 | 139 | # example below applies default value to $filename it is not supplied by an option 140 | # or inherited in the environment 141 | defaultfile=$HOME/.bashrc 142 | ## parse options here 143 | filename=${filename:-"$defaultfile"} 144 | 145 | # ${var:+alternate}, ${var+alternate}: Use Alternate Values 146 | # substitutes an alternate value if the parameter is not empty or, without a colon, if it is set. 147 | var= 148 | ./expansion.sh "${var:+alternate}" # var is set but empty 149 | # :: 150 | 151 | var=value 152 | ./expansion.sh "${var:+alternate}" # var is not empty 153 | # :alternate: 154 | 155 | # without the colon, alternate is used if the variable is set, even if it is empty 156 | var= 157 | ./expansion.sh "${var+alternate}" # var is set 158 | # :alternate: 159 | 160 | unset var 161 | ./expansion.sh "${var+alternate}" # var is not set 162 | # :: 163 | 164 | var=value 165 | ./expansion.sh "${var:+alternate}" # var is set and not empty 166 | # :alternate: 167 | 168 | 169 | # ${#var}: Length of Variable’s Contents 170 | # read passwd 171 | if [ ${#passwd} -lt 8 ] 172 | then 173 | printf "Password is too short: %d characters\n" "$#" >&2 174 | exit 1 fi 175 | 176 | # ${var%PATTERN}: Remove the Shortest Match from the End 177 | var=Toronto 178 | var=${var%o*} # shortest matching parttern is the final o 179 | echo $var # Toront 180 | 181 | var=${var%o*} # new shortest matching parttern from end is ont 182 | echo $var # Tor 183 | 184 | var=${var%0*} # newest shortest matching pattern from end is or 185 | echo $var # T 186 | 187 | 188 | # ${var%%PATTERN}: Remove the Longest Match from the End 189 | var=Toronto 190 | var=${var%%o*} # the longest matchin pattern from end is oronto 191 | echo $var 192 | # :T: 193 | 194 | # ${var#PATTERN}: Remove the Shortest Match from the Beginning 195 | var=Toronto 196 | var=${var#*o} # shortest matching pattern from the beginning is To 197 | echo $var 198 | # :ronto: 199 | 200 | # ${var##PATTERN}: Remove the Longest Match from the Beginning 201 | var=Toronto 202 | var=${var##*o} # longest matching pattern from beginning is Toronto 203 | echo $var # empty 204 | # :: 205 | # Often used to extract the name of a script from the $0 parameter 206 | scriptname=${0##*/} # /home/calistus/script => script 207 | 208 | # ${var//PATTERN/STRING}: Replace All Instances of PATTERN with STRING 209 | 210 | # since ? matches any character, it can be used to hide password 211 | passwd=zxQ1.=+-a 212 | printf "%s\n" "${passwd//?/*}" 213 | # ********* 214 | 215 | # ${var:OFFSET:LENGTH}: Return a Substring of $var 216 | var=Toronto 217 | ./expansion "${var:3:2}" 218 | # :on: 219 | 220 | ./expansion.sh "${var:3}" 221 | # :onto: 222 | 223 | # A negative OFFSET is counted from the end of the string. If a literal minus 224 | # sign is used (as opposed to one contained in a variable), it must be preceded 225 | # by a space to prevent it from being interpreted as a default expansion: 226 | var=Toronto 227 | ./expansion.sh "${var: -3}" 228 | # :nto: 229 | 230 | # ${!var}: Indirect Reference 231 | x=yes 232 | a=x 233 | ./expansion.sh "${!a}" 234 | # :yes: 235 | 236 | 237 | -------------------------------------------------------------------------------- /file-expressions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # test-file: Evaluate the status of a file 3 | FILE=~/.bashrc 4 | if [ -e "$FILE" ]; then 5 | if [ -f "$FILE" ]; then 6 | echo "$FILE is a regular file." 7 | fi 8 | if [ -d "$FILE" ]; then 9 | echo "$FILE is a directory." 10 | fi 11 | if [ -r "$FILE" ]; then 12 | echo "$FILE is readable." 13 | fi 14 | if [ -w "$FILE" ]; then 15 | echo "$FILE is writable." 16 | fi 17 | if [ -x "$FILE" ]; then 18 | echo "$FILE is executable/searchable." 19 | fi 20 | if [[ -s "$FILE" ]]; then 21 | echo "$FILE exists and is not empty" 22 | fi 23 | else 24 | echo "$FILE does not exist" 25 | exit 1 26 | fi 27 | exit 28 | 29 | # Reading a File 30 | 31 | # Contents of kjv.txt: 32 | 33 | # Genesis:001:001:In the beginning God created the heaven and the earth. 34 | # Exodus:020:013:Thou shalt not kill. 35 | # Exodus:022:018:Thou shalt not suffer a witch to live. 36 | # John:011:035:Jesus wept. 37 | 38 | while IFS=: read book chapter verse text 39 | do 40 | firstword=${text%% *} 41 | printf "%s %s:%s %s\n" "$book" "$chapter" "$verse" "$firstword" 42 | done < "kjv.txt" 43 | # Genesis 001:001 In 44 | # Exodus 020:013 Thou 45 | # Exodus 022:018 Thou 46 | 47 | 48 | # cut 49 | # The cut command extracts portions of a line, specified either by character or 50 | # by field 51 | cut -c 22,24,26 "kjv.txt" # -c cut by character 52 | # ebg 53 | # hl 54 | # hl 55 | # p. 56 | 57 | cut -c -24 "kjv.txt" # negative value copies from the end upto the number 58 | # Genesis:001:001:In the b 59 | # Exodus:020:013:Thou shal 60 | # Exodus:022:018:Thou shal 61 | # John:011:035:Jesus wept. -------------------------------------------------------------------------------- /find-file.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # A script to find any file on a linux-based machine 3 | 4 | find / -iname $1 2> /dev/null #redirect any error to the null file 5 | -------------------------------------------------------------------------------- /ftp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to retrieve a file via FTP 3 | FTP_SERVER=ftp.nl.debian.org FTP_PATH=/debian/dists/stretch/main/installer- 4 | amd64/current/images/cdrom REMOTE_FILE=debian-cd_info.tar.gz 5 | ftp -n << _EOF_ 6 | open $FTP_SERVER 7 | user anonymous me@linuxbox 8 | cd $FTP_PATH 9 | hash 10 | get $REMOTE_FILE 11 | bye 12 | _EOF_ 13 | ls -l "$REMOTE_FILE" -------------------------------------------------------------------------------- /function.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | is_valid_ip() { 4 | case $1 in 5 | ## reject the following: 6 | ## empty string 7 | ## anything other than digits and dots 8 | ## anything not ending in a digit 9 | "" | *[!0-9.]* | *[!0-9]) return 1 ;; 10 | esac 11 | 12 | # Change the Internal Field Separator (IFS) to a dot, but only in this 13 | # function 14 | local IFS=. 15 | 16 | # Place the IP address into the postional parameters; after word splitting, 17 | # each element becomes a parameter 18 | set -- $1 19 | 20 | [ $# -eq 4 ] && # must be four parameters 21 | # each must be less than 256 22 | # A default of 666 (which is invalid) is used if a parameter is empty 23 | # All four parameters must pass the test 24 | [ ${1:-666} -le 255 ] && [ ${2:-666} -le 255 ] && 25 | [ ${3:-666} -le 255 ] && [ ${4:-666} -le 255 ] 26 | } 27 | 28 | for ip in 127.0.0.1 168.260.0.234 1.2.3.4 123.100.34.21 204.225.122.150 29 | do 30 | if is_valid_ip "$ip" 31 | then 32 | printf "%15s: Valid\n" "$ip" 33 | else 34 | printf "%15s: Invalid\n" "$ip" 35 | fi 36 | done 37 | 38 | 39 | # Check valid integer 40 | is_valid_integer() { 41 | case ${1#-} in # Remove any leading hyphen to accept negative numberss 42 | *[!0-9]*) false;; # the string contains a non-digit character 43 | *) true ;; 44 | esac 45 | } 46 | 47 | #Set Different Exit Codes 48 | range_check() #@ USAGE: range_check int [lo [high]] 49 | if [ "$1" -lt ${2:-10} ] 50 | then 51 | return 1 52 | elif [ "$1" -gt ${3:-20} ] 53 | then 54 | return 2 55 | else 56 | return 0 57 | fi 58 | #Return codes are a single, unsigned byte; therefore, their range is 0 to 255. 59 | 60 | -------------------------------------------------------------------------------- /giga2mega.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Convert Giga to Mega 3 | # the value to be converted must be passed to the script as argument 4 | 5 | GIGA=$1 6 | MEGA=$(($GIGA * 1024)) 7 | 8 | echo "$GIGA GB is equal to $MEGA MB" 9 | -------------------------------------------------------------------------------- /git-versions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # script to get all git versions from official git-scm website 3 | 4 | # check if wget is installed 5 | which wget &>/dev/null 6 | if [ $? -ne 0 ]; then 7 | echo "please install wget and retry" 8 | exit 1 9 | fi 10 | 11 | # remove old index.html file if it exists 12 | if [ -e "index.html" ]; then 13 | echo "Removing old index.html" 14 | rm -rf index.html 15 | fi 16 | 17 | url="https://mirrors.edge.kernel.org/pub/software/scm/git/" 18 | wget $url 19 | if [ $? -ne 0 ]; then 20 | echo "Unable to download git info from $url" 21 | exit 2 22 | fi 23 | 24 | declare -a git_vers #declare an arrary called git_vers to hold the versions 25 | echo "********* Collecting all git versions from git website. Please wait." 26 | while read line 27 | do 28 | git_vers+=($(echo $line | sed -n '/git-\([0-9]\+\.\)\+tar.gz/p' | awk -F '"' '{ print $2 }' | cut -c 5- | awk -F '.tar.gz' '{print $1}')) 29 | done < index.html 30 | 31 | echo "All available git versions are: " 32 | cnt=0 33 | no_vers=${#git_vers[*]} 34 | WIDTH=10 35 | for each_ver in ${git_vers[*]} 36 | do 37 | printf "%-*s %-*s %-*s %-*s %-*s\n" $WIDTH ${git_vers[$cnt]} $WIDTH ${git_vers[$((cnt+1))]} $WIDTH ${git_vers[$((cnt+2))]} $WIDTH ${git_vers[$((cnt+3))]} $WIDTH ${git_vers[$((cnt+4))]} 38 | cnt=$((cnt+5)) 39 | if [ $cnt -ge $no_vers ]; then 40 | break 41 | fi 42 | done 43 | -------------------------------------------------------------------------------- /if-statement.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # if-else statment 4 | if [ $(whoami) = "root" ]; then 5 | echo "You are root" 6 | else 7 | echo "You are not root" 8 | fi 9 | 10 | -------------------------------------------------------------------------------- /kjv.txt: -------------------------------------------------------------------------------- 1 | Genesis:001:001:In the beginning God created the heaven and the earth. 2 | Exodus:020:013:Thou shalt not kill. 3 | Exodus:022:018:Thou shalt not suffer a witch to live. 4 | John:011:035:Jesus wept. -------------------------------------------------------------------------------- /leap-year.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script to determine whether or not a year is a leap year 3 | # A year is a leap year if it satifies the following conditions: 4 | # 1. Year is a multiple of 400 5 | # 2. Year is a multiple of 4 and not multiple of 100 6 | 7 | year=$1 8 | 9 | if [ $(($year % 400)) -eq 0 ]; then 10 | echo "$year is a leap year." 11 | elif [ $(($year % 4)) -eq 0 ] && [ $(($year % 100)) -ne 0 ]; then 12 | echo "$year is a leap year." 13 | else 14 | echo "$year is not a leap year." 15 | fi -------------------------------------------------------------------------------- /loop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # C-Style Loop 4 | for ((i=0;i<10;i++)); do 5 | echo "Hello, Friend $i" 6 | done 7 | 8 | # List/Range-Style loop 9 | for i in {0..9}; do 10 | echo "Hello, Friend$i" 11 | done 12 | 13 | # Iterate through a list of files 14 | for i in /var/*; do 15 | echo $i 16 | done 17 | 18 | # While Loops 19 | # while [ condition ]; do 20 | # [commands] 21 | # done 22 | 23 | num=1 24 | while [ $num -le 10 ]; do 25 | echo $(($num * 3)) 26 | num=$(($num+1)) 27 | done 28 | 29 | # Until Loops 30 | # until [ condition ]; do 31 | # [commands] 32 | # done 33 | 34 | num=1 35 | until [ $num -gt 10 ]; do # It evaluates as long as condition is false. It is the oppostie of while loop 36 | echo $(($num * 3)) 37 | num=$(($num+1)) 38 | 39 | # Traverse Array 40 | prime=(2 3 5 7 11 15 17 19 23 29) 41 | for i in "${prime[@]}"; do 42 | echo $i 43 | done 44 | 45 | # break statement 46 | for ((i=1; i<=10; i++)); do 47 | echo $i 48 | if [ $i -eq 3 ]; then 49 | break # exit the loop 50 | fi 51 | done 52 | 53 | # continue Statement 54 | for ((i=1; i<=10; i++)); do 55 | if [ $(( $i % 2)) -eq 0 ] 56 | continue # skip the current iteration. It does not exit the loop 57 | fi 58 | echo $i 59 | done 60 | 61 | 62 | function match_uppercase() { 63 | #typeset -a data=("$@") 64 | # Write your code here 65 | cnt=0 66 | for value in "${my_array[@]}"; 67 | do 68 | if [[ value =~ [[:upper:]] ]]; then 69 | cnt=$((cnt+1)) 70 | fi 71 | done 72 | echo $cnt 73 | } 74 | 75 | match_uppercase johny Mary Jane godwin -------------------------------------------------------------------------------- /nested-if-statement.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Nested If Statement 3 | 4 | TEMP=$1 # to be passed toscript as an argument 5 | 6 | if [ $TEMP -gt 5 ]; then 7 | if [ $TEMP -lt 15 ]; then 8 | echo "The weather is cold" 9 | elif [ $TEMP -lt 25 ]; then 10 | echo "The weather is nice" 11 | else 12 | echo "The weather is hot" 13 | fi 14 | else 15 | echo "It is freezing outside ... " 16 | fi -------------------------------------------------------------------------------- /net-salary.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Calculate the net salary of an employee 3 | 4 | echo "Enter your monthly gross slaray: " 5 | read msal 6 | echo "Please enter your tax rate (in percentage): " 7 | read tax 8 | 9 | gross=$(echo "$msal*12" | bc -l) 10 | net=$(echo "scale=2; $gross - $tax/100*$gross" | bc -l) 11 | 12 | echo "Your total net annual salary is: $net" -------------------------------------------------------------------------------- /no-of-cpu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Print the number of CPU Cores 3 | echo -n "Number of CPU(s): "; nproc -------------------------------------------------------------------------------- /ping-servers.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # script that pings every single server in the 23.227.36.x subnet 3 | # where x is a number between 0 and 255. If a ping succeeded, it displays the 4 | # statement "Server 23.227.36.x is up and running". Otherwise, if a ping 5 | # failed, it displays the statement "Server 23.227.36.x is unreachable" 6 | 7 | for((i=0;i<256;i++)); do 8 | ping -c 1 23.227.36.$i >> /dev/null 2>&1 9 | if [ $? -eq 0 ]; then 10 | echo "Server 23.227.36.$i is up and running." 11 | else 12 | echo "Server 23.227.36.$i is unreachable." 13 | fi 14 | done 15 | 16 | -------------------------------------------------------------------------------- /project.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Program to output a system information page 3 | TITLE="System Information Report for $HOSTNAME" 4 | CURRENT_TIME="$(date +"%x %r %Z")" 5 | TIMESTAMP="Generated $CURRENT_TIME, by $USER" 6 | 7 | report_uptime(){ 8 | cat << _EOF_ 9 |
$(uptime)> 11 | _EOF_ 12 | return 13 | } 14 | 15 | report_disk_space () { 16 | cat <<- _EOF_ 17 |
$(df -h)19 | _EOF_ 20 | return 21 | } 22 | 23 | report_home_space () { 24 | cat << _EOF_ 25 |
$(du -sh /home/)27 | _EOF_ 28 | return 29 | } 30 | 31 | cat << _EOF_ 32 | 33 | 34 |
$TIMESTAMP
39 | $(report_uptime) 40 | $(report_disk_space) 41 | $(report_home_space) 42 | 43 | 44 | _EOF_ -------------------------------------------------------------------------------- /pytest.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3, 4] 2 | b = [sum(a[0:x+1]) for x in range(0, len(a))] 3 | print(b) 4 | 5 | array1 = [1, 2, 3, 4, 5] 6 | arrav2 = array1 7 | arrav2[0] = 0 8 | print(array1) 9 | 10 | import re 11 | res = re.findall('welcome to Turning', 'welcome', 1) 12 | print(res) 13 | 14 | print([i.lower() for i in "TURING"]) -------------------------------------------------------------------------------- /special-bash-variables.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "The name of the script: $0" 3 | echo "The number of arguments passed to the script: $#" 4 | echo "The values of all arguments passed to the script: $@ or $*" 5 | echo "The process ID of current shell: $$" 6 | echo "The last argument to the command $_" 7 | [ 1 -gt 2 ] 8 | echo "The exit code of the last executed command $?" -------------------------------------------------------------------------------- /strings.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Get the string lenght $(#string) 4 | distros="Ubuntu" 5 | echo ${#distros} 6 | 7 | # Concatenate Strings 8 | str1="Mr." 9 | str2=" Robot" 10 | str3=$str1$str2 11 | echo $str3 12 | 13 | # Append operator += 14 | var=abc 15 | var+=def 16 | echo "$var" 17 | # abcdef 18 | 19 | 20 | 21 | # Finding Substrings 22 | # expr index string substr 23 | str="Bash is Cool" 24 | expr index "$str" "Cool" # returns the index number of the 1st character of substring 25 | 26 | # Extract Substring 27 | # ${string:begin:end} 28 | foss="Fedora is a free operating system" 29 | echo ${foss:0:6} #extract from the begining to index 6 (Fedora) 30 | echo ${foss:12} #extract from index 12 to the end (free operating system) 31 | echo ${foss:17:9} #extract from index 17 upto 9 characters after that (operating) 32 | 33 | string="01234567890abcdefgh" 34 | echo ${string: -7:2} # bc 35 | 36 | # Replace Substrings 37 | # ${string/old/new} 38 | foss="Fedora is a free operating system" 39 | echo ${foss/free/popular} 40 | 41 | # Delete Substring 42 | # ${string/substr} 43 | fact="Sun is a big star, very big" 44 | fact=${fact/big} # deletes the first occurrence of "big" 45 | 46 | cell="080-334-1712" 47 | cell=${cell/-} # removes the first occurence of substr 48 | cell=${cell//-} # removes all occurrences of substr 49 | 50 | # Convert to Uppercase and Lowercase Letters 51 | legend="john nash" 52 | actor="JULIA ROBERTS" 53 | 54 | echo ${legend^^} # convert all to uppercase 55 | echo ${actor,,} # convert all to lowercase 56 | 57 | echo ${legend^} # convert first letter to uppercase 58 | echo ${legend,} # convert first letter to lowercase 59 | 60 | echo ${legend^^[jn]} # convert all occurence of substr to uppercase 61 | 62 | # Bash script to trim strings 63 | # 1. Remove all astericks (*) in the string 64 | # 2. Change all letters to uppercase 65 | # 3. Output the updated string to the terminal 66 | 67 | echo -n "Please enter a string: " # -n do not print the trailing newline character 68 | read str 69 | str=`echo ${str//\*}` 70 | str=`echo ${str^^}` 71 | echo "Updated string: $str" 72 | 73 | # check valid names 74 | [!a-zA-Z_]* # does not begin with a small letter, a capital letter or underscore 75 | *[!a-zA-z0-9_]* # does not contain a small letter, a capital letter or underscore 76 | 77 | # Check whether a directory is included in the PATH variable: 78 | if ! echo ${PATH} | grep -q /usr/games 79 | then 80 | PATH=$PATH:/usr/games 81 | fi 82 | 83 | # compare lexical positions of string 84 | str1="abc" 85 | str2="def" 86 | test str1 \< str2 # \ is used to escape < to avoid redirection 87 | echo "exit status for str1 < str2: $?" 88 | 89 | # Repeat Character to a Given Length 90 | repeat_character() 91 | { 92 | #@ USAGE: repeat_character string number_of_times 93 | repeat= 94 | while (( ${#repeat} < $2 )) 95 | do 96 | repeat+=$1 97 | done 98 | } 99 | # test the repeat_character function 100 | repeat_character % 40 101 | printf "%s\n" "$repeat" 102 | # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 103 | 104 | # repeat_character function can be sped up by concatenating more than one 105 | # instance in each loop so that the length increases geometrically. Then trim 106 | # it down to desired length. 107 | repeat_character2() { 108 | #@ USAGE: repeat_character string number_of_times 109 | repeat2=$1 110 | while (( ${#repeat} < $2 )) # loop until string exceeds desired length 111 | do 112 | repeat2=$repeat2$repeat2$repeat2 113 | done 114 | repeat2="${repeat2:0:$2}" # trim to desired length 115 | } 116 | # test the repeat_character2 function 117 | repeat_character2 % 40 118 | printf "%s\n" "$repeat2" 119 | 120 | 121 | # Print a warning message with a border and a beep 122 | alert() { 123 | #@ USAGE: alert message border 124 | # it calls the repeat_character function 125 | repeat_character2 "${2:-#}" $(( ${#1} + 8 )) # adds 8 to the length of message 126 | printf '\a%s\n' "$repeat2" # \a is BELL 127 | printf '%2.2s %s %2.2s\n' "$repeat2" "$1" "$repeat2" 128 | printf '%s\n' "$repeat2" 129 | } 130 | 131 | alert "double-check before you submit" "#" 132 | ###################################### 133 | ## double-check before you submit ## 134 | ###################################### 135 | 136 | 137 | ############### 138 | # Test String # 139 | ############### 140 | test "$a" = "$b" 141 | [ "$q" != "$b" ] 142 | 143 | # the -z and -n operators return successfully if their arguments 144 | # are empy or nonempty 145 | [ -z "" ] 146 | echo $? # 0 147 | 148 | test -n "" 149 | echo $1 # 1 150 | 151 | 152 | -------------------------------------------------------------------------------- /test-conditions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Test Condtions 3 | # for full test options: 'man test' on a linux/mac terminal 4 | 5 | if [ $# -ne 1 ]; then 6 | echo "Error: Invalid number of arguments" 7 | exit 1 8 | fi 9 | 10 | file=$1 11 | 12 | if [ -f $file ]; then 13 | echo "$file is a regular file" 14 | elif [ -L $file ]; then 15 | echo "$file is a soft link" 16 | elif [ -d $file ]; then 17 | echo "$file is a directory" 18 | else 19 | echo "$file does not exist" 20 | fi 21 | 22 | dir="/Users/calistus/Documents" 23 | if [ -d "$dir" ] && cd "$dir" 24 | then 25 | echo "$PWD" 26 | fi 27 | 28 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #typeset -a data=("$@") 3 | # Write your code here 4 | cnt=0 5 | my_array=("Akwa" 'udo' 'Mmiri' 'John') 6 | for value in "${my_array[@]}" 7 | do 8 | if [[ "$value" =~ [A-Z] ]]; then 9 | cnt=$((cnt+1)) 10 | fi 11 | done 12 | echo $cnt -------------------------------------------------------------------------------- /variables.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Hello stranger, what's your name?" 3 | read name 4 | echo "Hello, $name!" 5 | -------------------------------------------------------------------------------- /word-count.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Count the number of lines in a file 3 | # Other options could be: 4 | # -w for number of words, 5 | # -m for no. of characters 6 | 7 | nlines=$(wc -l < $1) 8 | echo "There are $nlines lines in $1" 9 | --------------------------------------------------------------------------------