+ All Categories
Home > Documents > An Introduction to Bash - UTEP MATHEMATICS€¦ · What is a shell script? It is basically a...

An Introduction to Bash - UTEP MATHEMATICS€¦ · What is a shell script? It is basically a...

Date post: 21-Aug-2018
Category:
Upload: vuongkhue
View: 213 times
Download: 0 times
Share this document with a friend
34
An Introduction to Bash Luis Gutierrez
Transcript

An Introduction to Bash

Luis Gutierrez

What is a shell script? It is basically a program that is meant to run in the command line/terminal. It helps to automate tasks or procedures. You can use control flow statements (if, while) You can use variables and functions There are different types of shells such as:

bash, csh, sh, etc.

Objectives of this talk 1. Quick overview of the shell (Commands

and mechanisms) 2. Introduction to Bash 3. Variables (local and reserved) 4. Input/output commands 5. Using patterns and regular expressions 6. Control flow statements

Getting started with shell �  How to know what type of shell are you using:

�  Command: � echo $SHELL

�  Output: �  /bin/bash

�  How to know what shells are available: �  Command:

� cat /etc/shells �  Output:

/bin/bash /bin/csh /bin/ksh /bin/sh /bin/tcsh /bin/zsh

Getting started with shell � Common commands:

�  List elements in directory: � Command: ls

�  Change to a different directory: � Command: cd <directory>

�  Example: cd /Users/luis/Desktop

�  See full path of current directory: � Command: pwd

�  Output: /Users/luis/Documents

Getting started with shell �  Print contents of a file in the command line:

�  Command: cat <file name> �  Example: cat output.txt

�  Copy a file: �  Command: cp <source> <destination>

�  Example: cp myfile.txt ~/Desktop/ �  Remove a file:

�  Command: rm <file to be removed> �  Example: rm myfile.txt

�  What about directories/folders? �  To remove or copy a directory:

�  cp –r <source> <destination> �  rm –r <file to be removed>

�  NOTE: never use the following command: �  rm –rf /

Getting started with shell �  Creating a directory/folder:

� Command: mkdir <new directory> �  Example: mkdir /Users/luis/Desktop/MyNewFolder

� What if don’t know how to use a command?

� You can always refer to the man pages: �  Command: man ls �  Output:

Getting started with shell �  What happens when you login to the shell?

�  The following files are executed: �  /etc/profile � ~/.profile � ~/.bashrc � ~/.bash_profile

�  If you need to execute a command when you login to the shell, you will need to add them either to “~/.profile” or “~/.bashrc” file. (We will see later why this is useful).

�  NOTE! Be very careful while editing the previous files, as it might cause trouble in your terminal

Getting started with shell scripting �  A common shell script looks like the following:

#!/bin/bash # This script takes the first and second argument and # prints it. first=$1 last=$2 echo “Hello $first $last !”

Getting started with shell scripting � You can edit your bash script in your

favorite text editor � To run your bash script you have the

following options � bash script.sh

�  Or � chmod +x script.sh �  ./script.sh

� Let’s run the previous script

Local Variables � To store data in a variable the syntax is like

the following: �  variableName=“Hello World”

� Please note that the following is incorrect: �  variableName = “Hello World”

� To print the information: �  echo $variableName

� Please note that the following is incorrect: �  echo variableName

Types of variables �  Array/string

�  a=5; a+=2; echo $a; � Output: 52

�  Associative array (only in version 4) �  declare –A aa �  aa[hello]=world �  aa[ab]=cd �  echo ${aa[hello]}

�  Integer �  Declare –i a=5; a+=2; echo $a;

� Output: 7

Global/Reserved Variables �  Global/reserved variables are the ones that

your current shell provides for you. Common variables include: �  $PATH = The directories in which the shell will look

for executable programs �  $HOME = The path of the home directory of the

current user �  $TMPDIR = The path where the shell stores

temporary files �  $BASH_VERSION = The current shell version �  $PWD = The path of your current working

directory

Quoting in shell � echo “$PATH” � echo $PATH

�  Output: Actual value of path

� echo ‘$PATH’ � echo \$PATH

�  Output: $PATH

� echo “ ‘$USER’, ‘$USERs’, ‘${USER}s’” �  Ouput: ‘luis’, ‘ ’, ‘luiss’

Handling input/output

Redirecting input/output in shell �  Redirecting output to a file:

�  pwd > mypath.txt

�  Redirecting output to a command: �  ls -l | wc –l

� Output: Number of files in your current directory

�  Appending to a file: �  pwd >> mypath.txt

�  Redirecting input: �  command < inputFile.txt

Handling command line arguments

�  $1, $2, $3,..., $9 �  The command line arguments

�  $* �  All command line parameters or arguments.

�  $# �  Number of parameters.

�  $- �  Flags supplied to the shell.

�  $? �  holds the return value set by the previously executed

command. �  $$

�  process number of the shell. �  $@

�  All command line parameters or arguments.

Sample file for handling arguments

#!/bin/bash echo ”Script name : $0” echo “First argument : $1” echo ”Number of arguments : $#” echo “Flags used: $-” echo "The value of all command-line arguments: $*" echo "The value of all command-line arguments: $@”

Asking for user input � Used by the command “read” � Example:

#!/bin/bash/ echo “What is your age” read age echo “Your age is $age”

Searching text in files �  In this case, the command that comes

handy is “grep” � According to the man pages of grep,

grep is a file pattern searcher. � Common usage of grep:

�  grep <flags> <pattern> <file>

Using grep to search files � Searching in current folder:

�  grep –r wordToSearch .

� Searching in a specific file: �  grep wordToSearch Main.cpp

� Searching in a specific directory: �  grep –r wordToSearch directory/

Using Patterns � Patterns come very handy when

searching for specific strings. � For example, if you have 495 files named

as follows: �  Image001.jpg �  Image002.jpg … �  Image495.jpg

Using patterns �  * - preceding items

�  ls *.txt �  . – any character

�  grep –r “test” . �  [] – range of characters

�  ls [a-r]* �  ls [a-cp-z]*

�  [[]] – classes of characters �  ls [[:digits:]]*

�  \< \> �  grep ‘\<c…h\>’ file.txt �  grep ‘\<c.*h\>’ file.txt

Examples of patterns �  grep ‘\<c…h\>’ /usr/share/dict/words

�  Output: �  Catch �  Clash �  Cloth �  Coach

�  grep ‘\<c.*h\>’ /usr/share/dict/words �  Output:

�  Caliph �  Cash �  Catch �  Cheesecloth �  Cheetah

Control Flow statements

Conditionals �  [ STRING1 == STRING2 ] �  [ STRING1 != STRING2 ] �  [ STRING1 < STRING2 ] �  [ STRING1 > STRING2 ] �  [ NUMBER1 op NUMBER2 ] where op:

-eq -ne -lt -le -gt -ge

�  [ !EXPR ] �  [ (EXPR) ]

Conditionals on files �  [ -a FILE ]

�  True if FILE exists �  [ -r FILE ]

�  True if FILE is readable �  [ -s FILE ]

�  True if FILE size is greater than zero �  [ -w FILE ]

�  True if file is writable �  [ -x FILE]

�  True if file is executable

If statement If [ a == b ]

then echo “a equals b” else

echo” “a not equals b” fi If [ a == b ]

then echo “a equals b” elif [ a == c ]

then echo “a not equals b” fi

Case statements read option case $option in

1) echo “you selected option 1” ;; 2) echo “you selected option 2” ;; *) echo “your option is not available” ;;

esac

For loops for (( i=1; i > 0; i++ ))

do echo “iteration number $i”

done

For loops in associative arrays �  For example, when you have:

�  array[test1]=9; array[cat]=42; array[dog]=3243

for i in “${!array[@]}” do

echo “key : $i” echo “Value: ${array[$i]}”

done �  In this case, if we remove “!” we will get the values

While and Until loops $i=“0” while [ $i –lt 4 ] do

i=$[$i+1]

done

Wrapping up: Last Example � Using previous tools, a more complete

and useful script depending on user necessities

� Handling complex data structures is not possible

References � http://www.tldp.org/LDP/Bash-Beginners-

Guide/html/

� http://mywiki.wooledge.org/BashGuide/

� https://help.ubuntu.com/community/Beginners/BashScripting


Recommended