Bash script with various commands



Download 340.17 Kb.
Page2/2
Date09.06.2018
Size340.17 Kb.
#53735
1   2

The BASH Script file



  • other than the first line and chmod, very similar to other languages

  • no main()

  • starts from the top

  • in Emacs, adding the #/bin/… does make the text turn colors

  • can also run with sh command

    • sh




File setup

helloWorld.sh



helloWorld



helloWorld2


Shebangs


  • think of it as C++/Java includes or imports

    • built-in features, functions, etc…

  • there are different versions

    • bash

    • sh

    • ksh

    • csh

    • etc…

  • watch for sh and bash

    • sh = Shell Command Language

    • bash = an implementation (of many) of sh

    • were very similar

    • but bash has started to drift away from sh

    • will see many older sites use sh (when they mean bash)

Variables, Expressions and Math



  • variables have no defined type

    • can change (reset) at will

  • variable declaration (or reset!!)

    • a=23

    • a=“What up” b=36 c=Hello

      • no spaces around the = sign

      • multiple variables can be declared on one line

      • strings do not need “ unless it is multiple tokens

  • but using the variable requires a $ marker in front

    • echo $a

      • again, no space after the $

  • use in mathematics

    • all symbols are the same in other languages except multiplication

      • \* is used for multiplication since * is a wildcard

      • \ in front of parentheses \( \)

    • the command “expr” is used to solve integer equations

  • reading values from the keyboard

    • read command used with a variable will assign the value

    • read var #yes, no $

  • incrementing uses expr command




Basic integer math with variables

var=12


answer=`expr $var + 1`

echo $answer






  • can’t do floating point arithmetic natively in bash

    • have to use a command line tool “bc” or AWK

      • precision calculator language

    • var=`expr $var + 1.5` (did not work)

      • ` are smart quotes

    • answer=$(bc <<< "3.4+7/8-(5.94*3.14)")

      • values can be replaced with variables




Solving for the Hypotenuse

a=3


b=4

c=$(bc <<< "sqrt($a*$a+$b*$b)")

echo $c


Change the code above for the user to enter sides A and B.
Displaying and retrieving values

  • echo is used in several forms to display simple text to variables

  • simple test examples

    • echo “Welcome class”

    • echo “$var is 40 years old”

    • print “Thank you very much”

    • echo “$var is 40 years old \c”

      • \c == no line break

If else statements

Add this below

https://www.cyberciti.biz/faq/linux-unix-shell-check-if-directory-empty/




  • same as it always was

  • keyword then has to be on the next line by itself

  • overall layout is minorly different with “then” and “fi” at end

    • has to be on the next line

  • condition uses [ ]s and must be spaces before and after [ ]

    • no ( )s




If else example

if [ $answer -lt 60 ]

then # then is on a separate line

echo "You got a F!!"

elif [ $answer -lt 70 ]

then


echo "You got a D!!"

elif [ $answer -lt 80 ]

then

echo "You got a C!!"



elif [ $answer -lt 90 ]

then


echo "You got a B!!"

else


echo "Yeah, not in Lupoli's class."

fi


[] vs [[]]



[] vs. [[]]

 

Contrary to [[[ prevents word splitting of variable values. So, if VAR="var with spaces", you do not need to double quote $VAR in a test - eventhough using quotes remains a good habit. Also, [[ prevents pathname expansion, so literal strings with wildcards do not try to expand to filenames. Using [[== and != interpret strings to the right as shell glob patterns to be matched against the value to the left, for instance: [[ "value" == val* ]].

Cases statements



  • works the same way, just the overall setup is different




Case Statement Examples

Example 1

echo "Enter a letter"

read letter


case $letter in

[[:lower:]])

echo "lowercase letter"

;;

[[:upper:]])



echo "uppercase letter"

;;

[0-9])



echo "digit"

;;

?)



echo "error: $letter is not a source or object file."

;;

esac



Example 2

case $filename in

*.c )


echo "filename's extension was .c"

;;

*.s )



echo "filename's extension was .s"

;;

*.o )



echo "filename's extension was .o"

;;

* )



echo "error: $filename's extension has no match."

Esac





If statements with RegEx

https://stackoverflow.com/questions/16576467/shell-scripting-regex-in-if-statement


https://stackoverflow.com/questions/18709962/bash-regex-if-statement

Logical Operators



  • work the same but really look like operators (functions)

  • Integers

    • require commands shown below

  • Strings

    • require [[ ]]

    • use same <,>, !=, = (==), etc.. symbols you are used to

  • for real numbers, convert to string, then compare


explain the difference between the &&, ||, -a, and -o Unix operators?
Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.



  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&||<, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].



Coding Differences in comparing different types

Integers

Strings

Floats

if [ $answer –lt 100 ]

then




if [[ $var1 < $var2 ]]

then
[[ used for String comparison ]]



tar1=53.56

tar2=53.56


if [[ "$tar1" < "$tar2" ]]

then


echo "tar1 < tar2"

elif [[ "$tar1" > "$tar2" ]]

then

echo "tar1 > tar2"



else # [ $tar1 == $tar2 ]

echo "tar1 == tar2"



fi




The space must be there!!



Comparison

Datatype

Comparison Operator

meaning

Example

String

!










-n










-z

null string?

[[ -z $str1 ]]




=










!=










<, >




if [[ $var1 < "ZZ" ]]

Integers

-lt

<

if [ $answer -lt 60 ]




-le

<=







-gt

>







-eq

==







-ne

!=







-a

AND







-o

OR




File

-d

FILE exists and is a directory







-e

FILE exists

if [ -e $filename ]




-r

FILE exists and the read permission is granted







-s

FILE exists and it's size is greater than zero







-w

FILE exists and the write permission is granted







-x

FILE exists and the execute permission is granted




Floats

using AWK






Debugging conditions



  • since the operators vary drastically, we can use the Linux command “test”




Using Test to Debug



While loops and reading from files



  • same as many languages, will need grep/awk to break up the data for complex applications

  • using the read as a condition

    • if it can’t read any more line, then it will stop

  • the value read in will be stored in the variable “line” below

    • notice line has a $ after that line







#file2 declared above
# while loop

while read line

do

# display line or do something on $line



echo "$line"

pts adduser -group slupoli:cs341staff -user $line

done <"$file2"

Pipes


  • when one solution needs another

  • statement 1 would give input to statement 2 to work on

  • also need ` around it all to complete correctly

`(statement 1) | (statement 2) `


Strings

  • ASCII comparison

  • lots of built-in functions

Command line arguments



in 19 – 4:00 and 20, and 22

good for what I want now!!
“Set” stuff @ 3:30

File IO Stuff


>> used to append to END of the file

[slupoli@linux2 fileIO]$ set $term = F15

[slupoli@linux2 fileIO]$ echo "well $term" >> test.txt

[slupoli@linux2 fileIO]$ echo "well shit" >> test.txt


all of 47

exec < $filename redirects the input to grab from the filename

all of 49

3:00 in 49 uses a while loop smartly
File checking stuff

31 start at 2:30


-f check if a file exists
-d check if directory exist
-r , -w –x to check for different permissions
-s if file size > 0 (0 period sadly)

Loops in General

break and return work as usual

4:00 in 52


While Loops

complete example in 5:00 in 39



Until Loops

complete example in 4:00 in 40





For “in” Loops

complete example in 5:00 in 41


Grep


in 43
grep what_we_want file_from

-i is ignoreCase

-n line number where the match was found

-c how many lines matched

-v lines that did not match

-a processing text files


watch the combo -c –v is count of lines that DID NOT match

Internal Field Separator (Strings)

46


sed '/pattern to match/d' ./infile

CSH
Edit mode


csh -x HW1Grader
Run mode
source HW1Grader
getting input
set req = $<
Sources
BASH Tutorials

http://ryanstutorials.net/bash-scripting-tutorial/


http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/
http://www.yourownlinux.com/2015/04/sed-command-in-linux-append-and-insert-lines-to-file.html
SED (within BASH)

https://www.youtube.com/playlist?list=PLcUid3OP_4OW-rwv_mBHzx9MmE5TxvvcQ


Bash Stuff

https://www.youtube.com/playlist?list=PL7B7FA4E693D8E790


Floating point math

http://askubuntu.com/questions/229446/how-to-pass-results-of-bc-to-a-variable

CSH
CSH Stuff

http://faculty.plattsburgh.edu/jan.plaza/computing/help/tcsh.htm


Setting a variable

set a = 100 (in CSH)


@ a = “new value” (space after @, think of @ as reset in CSH)
( but && is AND in CSH)

Moving within directories using foreach



  • using the normal linux commands, nothing new

  • but looping through when an inner set of directories many contain consistent data can be done with a loop







foreach dir (*)
# all of these didn;t work

# if ( -e "/$dir/*A.pdf") then

# if ( -e "/$dir/*A.pdf") then

# if ( -f "./$dir/${work341}*A.pdf") then

# if ( -e "./$dir/"*"A.pdf") then

# if (ls ./${dir}/*A.pdf 1 > /dev/null 2>&1;) then


# this worked for an EXACT match

# if ( -f "./lm84880/HW2lm84880A.pdf") then


# VERSION A

if ( -f "./$dir/${work341}${dir}A.pdf") then

echo "moved *A* RUBRIC in $dir"

cd $dir/


cp ~/CMSC341/collection/HWs/rubrics/${work341}Agrade.txt .

sed -i "2 s/USERID/${dir}/" ${work341}Agrade.txt # write username in rubric

cd ../

else if ( -f "./$dir/${work341}${dir}B.pdf") then



echo "moved *B* RUBRIC in $dir"

cd $dir/


cp ~/CMSC341/collection/HWs/rubrics/${work341}Bgrade.txt .

sed -i "2 s/USERID/${dir}/" ${work341}Bgrade.txt

cd ../

else if ( -f "./$dir/${work341}${dir}C.pdf") then



echo "moved *C* RUBRIC in $dir"

cd $dir/


cp ~/CMSC341/collection/HWs/rubrics/${work341}Cgrade.txt .

sed -i "2 s/USERID/${dir}/" ${work341}Cgrade.txt

cd ../

else


echo "file not found in, putting all versions in"

cd $dir/


cp ~/CMSC341/collection/HWs/rubrics/${work341}Agrade.txt .

cp ~/CMSC341/collection/HWs/rubrics/${work341}Bgrade.txt .

cp ~/CMSC341/collection/HWs/rubrics/${work341}Cgrade.txt .

cd ../


endif

end

Sources
Shebang

https://en.wikipedia.org/wiki/Shebang_%28Unix%29


Variables

http://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in-a-bash-script


Strings

(comparing)

http://stackoverflow.com/questions/2237080/how-to-compare-strings-in-bash
Random values

http://tldp.org/LDP/abs/html/randomvar.html


[] and [[]]

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_02.html





Download 340.17 Kb.

Share with your friends:
1   2




The database is protected by copyright ©ininet.org 2024
send message

    Main page