CSC209 Shell Programming

What we will going to talk about?

Unix? Unix is a kind of OS system like Window. Why we need to learn Unix in 209? That was also my question, when I was starting this course. I think it is related with the history of C. C is essentially developed to work with Unix. Here, I wouldn’t explain a lot about very detail. I will just get the important point about Unix and Shell Programming. Let’s do this.

 Unix file system

To learn Unix file system, stand up and go outside and look at some trees! You might think I’m crazy but hell no. Unix file system just looks like upside down tree. The very first file that contains everything, we call this “root” and its name is “/”. Few directories are stemmed from the root tree, the important ones are “usr, “bin”. “bin” stands for “binaries” and “usr” stands for “users”. The reason they are important is bin contains important programs that user need to use to manipulate to Unix file system. (e.g., cp, ls ← don’t worry about this right now, you will learn soon) and “usr” contains “Home”  directory that usually contains all the subdirectories and files that users made. You might wonder why I’m keep saying “users” instead of “user”. It is because almost every computer has a capacity of having multiple users. So they have a  directory called “usr”(users) to store each user’s directory. So let’s say your Emily’s family share one computer and Emily’s mom usually don’t use computer so Emily’s father, Jack and Emily are only using it. Then in “usr” directory, there will be two sub directory called “Emily” and “Jack” if they set their first name as their user name.

Well, you said it’s upside down tree, but It’s not a real tree! What it is?

Yeah, you’re right. Unix file system is one big hierarchy of files and I was saying the structure of it, just looks like upside-down tree. But it’s not a real tree ,because Unix File system is entirely composed of files and file is a named collection of information. The file is stored at Disk(actual hard disk). There are 4 types of files in Unix system.

Ordinary File

Ordinary Files is like plain coffee, it has basic capacity as a file. (i.e., we can store text, program, some other data in it but that’s it)

     Directory File

Directory is a special type of file that has information about other files that it contains. Directory File doesn’t contain actual data of files it’s containing ,but contain ‘information’ of them (i.e., their name and their “inode”). What is inode? Well, I’ll talk about it later, but it’s just a pointer that is pointing to the place where actual data of a file is stored in a hard disk and inode also has all the other information of file except for its name and the actual data.

Device File

Device file is a file make users be able to communicate with actual devices (such as “printer” and “keyboard”). So in Unix, you can control all your device like you control your text file! (as long as you know how to use it well and I don’t yet.)

Link File

Link file is a file that has same i-node with the original file. What that means? You can make a link file for an ordinary file by typing “ln       original_file       link_file”. Then even though link_file has different name from the original file it actually points same chunk of disk that contains file contents.

Inode 

All file has it’s inode. i stands for index because each node has a special number like “index”. We called this index as I-number and it is for Unix OS to differentiate files in the disk .(i.e., so the actual file name is for human beings, then how computer connect inode and its file name? we’ll talk about it soon. ) inode contains ALL the information of file except for ‘file name’ and ‘file content’. That’s actually very natural that Inode doesn’t contain “file name” and “file content” ,because first of all “file content” is stored in the actual disk and Inode directs where the file content is stored in the disk. About file name, think about link file. Link file has a different name from the original file but it should have same inode to save computer memory. If inode contains file name, you need to make another Inode for all the link file ,even though the all the inodes point a same disk space!(What a waste!)

Inside of inode

So what exactly inode contains? inode contains file size, file owner, the group that file is belongs to, file access right, hard link count, time stamps(e.g., when is the last time of modification? etc..)

Well, if it doesn’t have a file name, how computer connect its file name and inode?

Well, each directory has a table that maps each file name and its inode. So if you refer one file by it’s name, computer recognize it by it’s inode.

How I should work with this i-node

You might want to work with this i-node since i-node has almost every data of file. How are you going to work with this data structure? There are several command you might be interested in.

1. ls command 

ls stands for “list file”. It lists information of files depends on what options you give to it.

If you type “ls -al”, you computer will list all the files in your working directory with it’s inode information. The output will be separated into 6 columns.  1st column: access permission, 2nd column: the number of  the hard link!  It has interesting feature you might be wonder so I’ll introduce later. 3rd column: owner, 4th column: size in bytes, 5th column: data and time modification and 6th column: name. If you make a directory in your file, then you can see that 2nd column for the directory is 2 by default it’s because first one hard link as itself and there is a hidden hard link called “.” in the directory. You can see this hard link if you type ls -a(“a” stands for all and it shows all the hidden files in the working directory to you.). So if you type “cd .” then you will stay in your working directory and a hard link for its parent is created by default named “..”. Hence when you create a sub-directory in your directory then you’re increasing the number of hard link of your directory. Because when you create a sub-directory, it will create a linked to its parent named “..”.  first column is also very interesting and “useful” because with this you can control the access permission of your file. Well, If you share a computer with your family using different usernames, you might have some files that you don’t want you’re parent to see. (Oh, come one.) So, you might want to change the permission for the file. First, let’s see how you can see the information of the permission. The outcome of the first column will be 10 characters that looks like “blah blah” first character of it(let’s say position 1), refers the type of the file. d: directory, -: ordinary file, l: symbolic link(is that different from the hard link? Yes. we will talk about it soon) position 2-4 : permission for the owner (r- read, w-write, x-execute), 5-7: permission for the other users in the same group(important one to know how to prevent your parent from checking some files ) 8-10: permission for all other users. – denotes the lack of the right. if there is – where there should be w then it means no permission for writing.

So how would you change this file permission? 

We can change the permission by using a command called “chmod(stands for change mode)”.

You can use the command like this way “chmod g-rwx filename” to prevent your parents from accessing some of your files. This means remove the permission of reading, writing and executing from your group.

Symbolic link (What makes symbolic link different from the hard link? )

I mentioned the symbolic link above but I haven’t explained what it is. Hence, let’s talk about it now. The concept of symbolic link is very similar with the’ short cut’. While hard link takes same amount of space as its original file symbolic link only takes as much as the path to the original file and while hard link can’t be linked to directory, symbolic link can be linked to directory. Symbolic link has only one data: “the path” to the original file. It’s like alias.  we call a collection of information as “a” (i.e., a is a file name) then make a hard link for a named b(i.e., then b just have a data that is “/usr/home/a”, assumed that we’re in a home directory, if we try to some operation on b, computer directly interpret that action is for a.) Since the data the symbolic link is different, it is natural that it has different inode from the original file.

Well, what’s the point of having  symbolic link, by the way?

Well, as I said, you can’t make a hard link for a directory because of the recursion problem.  Let’s say you have a hard link called b for directory a inside a. If I said try to delete b, then it should delete a, and to delete a, it should delete b……………….Super recursive. Since computer doesn’t want to resolve those case, it just excluded the case of directory having a hard link but except for “.” and “..”. Hidden hard link for directory. You can’t modify these two.  Since the symbolic link just refers the original file, so we need to worry about the recursion problem.  Also, it only takes little space of it, so you don’t need to worry about it’s taking much space. That’s the clever part of it.

How to navigate Unix File System?

In Unix, you’re supposed to surfing around your file system using console which is looks super cool but not very intuitive and sometimes dangerous! (One time, I deleted all my file because I typed one line (= rm -rf *) mistakenly and it wasn’t recoverable) However, it can be also powerful! In Window, you need click every time to manipulate your files and directories but just type one line, you can do everything! Anyway, let’s get back to our main point.

Emily

Music —-SecretePictureReading

(Big Bang, Epik High)      (Diary)       (Good-Memory)   (Poem, Novel,Comic book)

 (Love Dust, Ego)                                            (Pocket Monster)

I hope the tree structure that I made is understandable. Music have 2 drectories called Big Bang, Epik High(some bands I listen) and Big Bang have 2 files called Love Dust and Ego. So now, I’ll drop you some place in this file system and you need to surf to another place  that I order you to go. In this journey, you will learn how to navigate Unix file system. Please, survive! So first, I’ll drop you at “Big Bang” and you need to go to  “Epik High” directory by using just one line. How would you go? There are always 2 ways of approaching it. First using a absolute path! You can approach to the designated directory by typing “cd /usr/home/Emily/Music/Epik High” (cd stands for  “change directory”) but it’s too tedious to type all of them. Then you can type “relative path”!  Relative path is easy if you think that you’re going to Epik high from Big bang by your feet. So you need to first get out of Big Bang then you will be in Music and after you will go into the Epik High. That’s it. <Music → Epik High> How would you type this. To go to the parent directory (in this case, Music), you need to type two dots (=”..”). So you will type “cd ../EpickHigh” That’s it. But one more interesting is you can also type ~ to refer whole absolute path to you user directory (in this case “Emily”), so you can just type “cd ~/Music/Epikhigh” and it is same as you type “cd /usr/home/Emily/Music/Epik High”.

Command

We learn about how the file system is constructed, but How we will manipulate them. We use many interesting command to do that. We call these command as “software tools”! 

“To be good a good plumber, we need to know how to use tools and we need to eat a lot of mushroom! Yes, we must know how to use this tools in order to defeat the turtle monster and save our princess.

1. Pipe

The very first thing we will talk about is something called “pipe”. If you know Mario game little bit, you will know how the pipe magically works in the Mario world. If you don’t know, don’t worry I’ll tell you. After you clear one stage, there is a pipe. If you jump into the pipe you are sent to the next stage. That’s it. Interestingly, that’s how pipe works in Unix. If you pipe your output to somewhere then your out put became an input to the somewhere(So the Mario who finished a stage go to the next stage through a pipe and need to start  for the next stage.) I can actually explain more easy way if you want, by the way “|” is pipe in Unix,  2+3|+4 = 9 (you can’t do this in Unix but it’s just for helping your understanding ). It became 9, because the out put of 2 +3 = 5 became the input for “+ 4″after the pipe, so 5 +4 = 9.

The real example will be this, “cat somefile | sort” , then the line that I wrote will sort all the content in “somefile”.

2.command>file

You can see this as kind of pipe. It’s called redirection and it just redirect the output to the file. So if you type  “cat somefile> file” then it’s output will be redirected to the file. So if you open up the file, you can check the output. There are actually more  symbol like ‘>’ for redirection.  ‘>’ only redirect standard output(i.e., it doesn’t redirect any error, so if any error occur while running the command, the error message will not be redirected to file, so it will be just printed on your working console or standard output). If you want to redirect the error, too then you need to use “>&” instead of “>”. If you only redirect error message then you can do this! “2>”. Then it will redirect only error message.

I found this website has a such nice information of  redirection, so check it out. http://www.codecoffee.com/tipsforlinux/articles2/042.html

3.Filtering

Most of unix command are designated for filtering by our professor. Well, I guess that’s kind of make sense because all Unix system is composed of files and you want to manipulate content of it in your way to do something else. If you just want to see the content as it is, you can just double click it.  Since manipulating content is filtering, so I guess that’s why there are a lot of command for filtering. Okay, anyway “by an expert”(My prof), filtering is important from the perspective of software tool. Remember Mario? To save our princess, we need to hurry!

3-1. sort

sort is simple command. Guess what it does! Yup, it sort every output of file. So let’s say you have a file called “name_list” and its content is like below

“name_list’s content”

eddie Albert

Jason Alexander

fred Astaire

Don Ameche

I got some “celebrity” names that I don’t know anyone of them, from the website called “Totally Usless Knowlege!” I always found there are too much celebrities (who are famous for nothing) in North America and i found it’s pretty funny.  Anway, if I type sort  “name_list”, then the output will be

Don Ameche

Jason Alexander

eddie Albert

fred Astarie

done. sort is sensitive about case matter.  If you don’t want to care about (i.e., if you want to treat “a” and “A” equivalent, then you can just put one option which is “-f” and if you want to sort by their last name, you can just add one more option which is “-k2” (k stands for “key”))

3.1 – sed

“sed” stands for “stream editer”. What is stream? In our case, it refers characters in a file. So sed means just kind of editor that we can use to manipulate the characters in file.  There are few options that we can try for sed, but one thing that might be useful is “-s” and s stands for “substitute”. So let’s say you have a text file and you want to substitute some words in it. Then you can use this option. How would you use it. See below example.

Let’s say I had a file called file.txt and inside it’s like this

“unix sucks! Using unix is such a pain of ass. I need to learn something to use it. Why don’t you use window?

It’s easy and you just need to click a lot. I hate to learn unix stuff ,so I’ll just click a lot! why don’t you let me be stupid? “

Okay let’s change unix to mac ,then you can type sed ‘s/unix/mac’ file.txt.   If you didn’t know the whole spelling of unix you can still do the job using “regular expression”(I’ll talk about it later). It will change the first occurrence of  unix to mac. So the first line will be “mac sucks! Using unix …” but for most of case, you will probably change all the occurrence of unix then what should we do? We put “g” which stands for global at the and of the command like this.

sed’s/unix/mac/g’ file.txt

If you want to change specific nth occurrence for each line, you can use something called “flag”. Let’s say, you want to change all the 2th unix of each line. Then you can type this.

sed’s/unix/mac/2’file.txt

But what if you want to find 2th unix and want to change all the occurrence of unix after that? (but Not the first one) Then you can combine “flag” and global together. Like this,

sed’s/unix/mac/2g’ file.txt 

You might want to add some characters around unix instead of changing to something else, then you can use ‘&’.

sed’s/unix/{&}/g’ file.txt 

In this case, it will change all the unix → {unix}

What else you should know.. well I was doing my homework, I found the grouping things are pretty useful.

So let’s get back to the “name_list” file, if you still remember. I put some of people’s name that we don’t need to know(No offense for those people ,but it’s true. Why the hell I should know their names? Waste of my memory absolutely.)

So “name_list” has some people’s full name and we want change every line in to this form

“My first name is <first name> and my last name is <last name>”

So we will take a first name as ‘group 1’ and  the last name as ‘group 2’. What should we do? Check this out!

sed’s/\(.*\) \(.*\)/”My first name is \1 and my last name is \2″

.* is regular expression for any characters. Since we have a space between first name and last name, I just said that put all the characters before one space as “group 1” and put all the characters after one space as “group 2” and put those group nicely in the formatted string that I gave you. That is what I was said. We must put \ for parenthesis because we don’t want computer interprete that we want to look for literal “(.*)” (←What the heck  is this word) and we want them know that is for grouping.

If you want to see the replaced line, you can type this

sed -n ‘s/unix/mac/p’ file.txt

if you don’t put -n, it will print out all the lines once if the line hasn’t replaced yet, and twice if the line has changed.

You can use mutiple sed with pipe.

and what else you should know about sed.. hmm.

Oh! If you want to change only specific line then you can do this.

sed 3 ‘s/unix/mac/’ file.txt

,then it will only change the 3rd line.

Too much..? Well there are actually 4 things left that you should know…(see? file.txt is actually right. Unix sucks! Let me click a lot in Window, please! )

You can append a line(putting a line after  specific lines)

sed ‘s/unix/ a “putting this line after the lines that are including the word unix”‘ file.txt

You can insert a line (putting the line before specific lines)

sed ‘s/unix/ i  “putting this line before the lines that are including the word unix”‘ file.txt

You can change specific lines

sed’s/unix/c “Any line that contains unix will be changed to this line”‘ file.txt

wc(word count)

“wc” is a very useful tool, if you want to just check how many lines that you have sort of things. If you type “wc myfile.txt” and the output is 2 10 50 then that means there are 2 lines, 10 words and 50 characters. People only use how many lines do they have in their file since usually most data base each data just took one line for one entry ,so if you count the number of lines in your file, you can get how much data you have in your file. So to get the number of lines in your file, you need to type “wc -l myfile.txt”. That’s it.

grep

grep is a tool to print lines that matches some pattern that I’m looking for.

For example, let’s say I heard form my friend C that my friend A and B talked about me what they’re chatting on facebook, so I hacked one of their facebook and got the chatting file. There were 40000 lines! and I’m super lazy to check all of it. So I decided to use grep, since my name is “Yelim” so I just type ‘grep “Yelim” chatFile’ and I found a lot of lines that contains my name!  Like “I miss Yelim (;” I felt really good after seeing all the nice statements that my friends made about me. But my friend C said, they also talked about me in Google chat and since they stopped and started talked for few times for that day, they have few files that might contains some content about me. So I hacked one of the friend’s g-mail account and got some files named google_chat_1, google_chat_2… and so on. I felt too lazy to type grep command for each file. However, soon I found with grep you can search multiple files in once!

Just type this grep Yelim google_chat_*, then it will search all the file has the formation of google_chat_(some character).

But interestingly, I couldn’t find much contents about me. So I decided to case insensitive search!

grep -i Yelim google_chat_* 

And.. I found a lot bit bothering my mind.  Like.. “Hmm.. I thought Yelim was my friend….”

So I decided take a look at the context! To see the context I had to get the lines around the line that bugging me.

So, I typed “grep -i -C 2  Yelim google_chat_*” to look 2 lines before the line and 2 lines after the line.

So it was like this.

I miss her.

She never get back my message!

Hmm.. I thougth Yelim was my friend

dissapointing

but well she might be busy.

Yes (: I do have good friends. I realized that I should send their mail right away from now on.

Additionally, if you either only want to print 2 lines before or only 2 lines after,

you can use -A for after -B for before instead of -C

tr(translate)

head,tail

uniq

cmp

diff

comm

join

find

Regular expression 

There are only bunch of rules that we need to remember to use this expression ,so I’ll start by introducing useful example

1.[a-z]+:

will match one or more lowercase

2.[abc]:

will match either a or b or c

3.[^abc]:

will match any character except for a,b and c

4.[a-z]:

will match any one lowercase

5.[a-zA-Z0-9]:

will match any letter or digit

6. xyz|abc:

will be match either ‘xyz’ or ‘abc’

Quantifier example

To search a pattern more effectively, we use quantifier. Like find some pattern that has one or more a=> a+(here ‘+’ is a quantifier)

1. X?

X is optional, X is occur once or not

2.X*

X occurs zero or more time

3.X+

X occurs once or more

4.X{n}

X occurs exactly n times

5.X{n,}

X occurs n time or more time

6.X{n,m}

X occurs at least n times but not more than m times

Glob expression 

Some command like grep, sed allow user to use “Regex”(aka regular expression). However, most of command in shell scripting use “Glob expression”. Except for few commands, glob expression is mostly used for Unix Shell.(I need to check about this with my prof)Hence, there’s a reason to learn it.

In glob expression, there are 4 rules that you should remember!  

  • ‘*’ matches any number of any characters(Hence, *.c will match with yelim.c, Emily.c blahblah.c You.c or just .c)
  • ‘?’ matches any One character (Hence, ?.c will match a.c, b.c, c.c but not dd.c and not .c)
  • [list of chars] it will match if the pattern is matched using one of the char in the list. (e.g., a[1234].txt matches a1.txt, a2.txt, a3.txt, a4.txt )
  • [range] instead of writng all the possibilities like giving a list of chars, you can give a range! Like, [1-6] (e.g., a[1-4].txt will wield same conclusion with the example above)

Shell Programming

Now, finally you got all the tool to be a nice plumber!

“Then, let’s start shell programming!”

How you start shell programming?

But, before that what is shell?

//will write it later: shell is a program that make users interact hardware stuff and file system.

Why we need to put sh before type the name of shell script?

//I will write this also later, typing sh is just for running the script by using “Bourne shell”. There are few other shells so you need to specify which shell you’ll use.

Some specialty of “Bourne shell”

There is a specialty of “Bourne shell” that I want to introduce to you. It’s called “here-document”. Instead of making the shell read a file input. You can give some multiple line text to command right away. I think it’s better to explain by comparison with “csh(c-shell)”.

Let’s say you want to echo this multiple line below.

“Hi, my Korean name is Yelim.

My English name is Emily.

What will be my Chinese name?

Having multiple names are fun.

Because it makes me feel like I’m 007 B) Bang!”

In csh, you can’t do echo with this multiple lines in once, either you need to put echo for each line or you need to put this lines in a file and “cat” it.

However messing up with file and putting a echo for every single line seems daunting. So our Bourne shell has its specialty called “Here-Document”. You can echo it by this way,

echo<<EOF

“Hi, my Korean name is Yelim.

My English name is Emily.

What will be my Chinese name?

Having multiple names are fun.

Because it makes me feel like I’m 007 B)! Bang!”

EOF

“EOF” just let echo know that where is the start of the file and where is the end of file.

Isn’t that nice, huh? As one lazy person, I think it’s pretty nice.

Finally, let’s start?

Path

First, you need to specify the path that computer will search in order to get the files of programming(e.g., usually command like “cat”, “echo” etc) that you will use in your shell script. You can set your path like below.

“PATH=/bin:/usr/bin”

file descriptor redirection

http://www.linuxnix.com/2012/02/linuxunix-redirection-operatorsfile-descriptors-explained-examples.html

http://docstore.mik.ua/orelly/perl/cookbook/ch16_08.htm

writing is in process

(I didn’t get this part quite yet, so I need to ask to a TA or my prof)

Variable

To do any some minor programming, you need to have some variables at least because the point of having a programming is making human work less and variable is doing same thing! make human work less. So let’s assign 3 to x.

You can type as x=3(just make sure that you don’t have any space between them b/c if you have any space the shell will recognize x as a command)

When you use it, you can call the x by using $ like this below.

“echo $x”

$ is just something to differentiate x as a character and x as a variable.

**Some important points of variable**

if you want to print $xy (i.e., 3y that means you want to print y right after $x without any space, remember $x was 3), but you can’t type echo $xy. Because, shell will interpret it as variable ‘xy’ not ‘x’. Hence, there is some special syntax that you can use. You can type “echo ${x}y”

You can have default value for the variable. Let’s say you’re supposed to get some value and put the value to a variable. But the input hasn’t come so the value is null. So what you can do is set a default value for that case. You can do that by typing this.

echo ${my_var-0}

If you didn’t specified your my_var, it will echo “0”.

Basic “if-else” statement 

Like any program language, shell scripting language also has “if- else statement”. Let’s take a look at a small example.

if  [$my_name = “yelim”];then

echo you’re right!

                                                            else

echo “get out (:”

                                                                          exit 1

                                                              fi

So if you don’t know my name, your program will be exit and get my nice “good-bye” message.

The interesting that we will look at here, is “fi” and “then”. You must put “;then” after if statement and “fi” after finishing all the if statement.

‘ ;’ in shell scripting

“;” can be used instead of new line.

“echo a; cat b.txt; sort c” is equivalent to

echo a

cat b.txt

echo c

Why do we need this? 

We might want to apply one command for the outcomes of all this command(then we do e.g., “echo a; cat b.txt; echo c)| sort” in that case you want to collect all the out put and sort together.

test command

sometimes we want to test some value is equal or less or bigger than something. Then we can use command “test” with some optin named -lt(less than), -eq(equal), -gt(greater than), -ne(not equal to), = for string comparison -ge(grater than or equal), -le(less than or equal ).

Let’s take an example of test.

We can use this test with “if”

if test 2 -le 3

                                                                             then

                    echo “yes, you’re right!”

                                                                             else

                                                                             echo “something wrong!”

Other than comparing strings, test has some more useful feature to use.

One is “test -f file.txt” it checks whether “file.txt” exists or not and if it exists, it returns “true” and I guess the “f” stands for “file”.

Another thing is “test -s file.txt” returns true if the file exists and the size of it is not zero. I guess ‘s’ refers to the “size”. (feel lazy)

You can use “OR” and “AND” like in most language!

 OR = “||” two pipe for some reason. (For my opinion, it looks like chopsticks)

And = “&&” It looks like two person sitting side by side.

Loop

Other than if and else statement “Loop” is the most basic needs for any programming language. Because programmers are super lazy. They are lazy so they don’t want to do repetitive work. They want Loop do the work. So like any other language, shell scripting language has two loops.

For loop and While loop

Let’s take a look at the for loop first.

for i in sleepy tired

                                                                        do

     echo “You can do it”

                                                                         done

for loop is pretty easy. It’s already Monday 2 a.m. So I’m really tired right now. So I put sleepy and tired for  “for loop”. Since there are 2 words, for loop will work for 2 times. That means it will print “You can do it” twice.

If you’re going to give an argument for “for loop”, then you don’t need to write the “in blah blah” part. You just need to type “for i” then it will execute “for loop” for the number of your argument.

Personally, I think While loop is more convenient and  more useful.

let’s say you want to to something for 10 times then you can do that with the for loop by typing

for i in 1 2 3 4 5…..10

                                                                      do

                                                                                 blah

                                                                      done

However, silly don’t do that. Do it like this.

                                                                        i=0

while test $i -lt 10

                                                                         d0

                                                                         blah

                                           i=`expr $i +1` #you must increase i by 1.

                                                                          done

Same simple structure, but don’t forget to initiate i first and increase it by 1. ` the back quote is like saying “this is command not string” to shell # I’ll explain later on more detail  and “#” is for commenting.

case

I didn’t use case when I was doing programming in java and python. But I used in my shell scripting when I was doing my assignment. Because it’s similar with “else if ” and shell scripting language doesn’t ahve a “esle if”. So it comes very handy. The example of case is like below.

case $1 in

sleep)

echo “I’ll be happy.”

study)

echo “My mom will be happy”

*)

echo “if I don’t sleep and I don’t study, mom and me both are not happy”

esac

Yes, I’m sleepy as hell. But I just want to finish this writing. So yes I’ll do what I need to do! It’s easy to understand how it works. What I thought interesting about it, is *) and esac.

*) includes all other remaining cases and esac actually same as “done” in loops. I don’t know why the developers chose “esac” instead of “done”. It’s VERY annoying to type it.

Shell function

I think we got the basic needs but to be a good programming language, it’s better to have a function. function is for me like a small and minor program inside a program. It’s also reduce our work.

You can make a function in this form below:

function_name(){

Things that you want to do in this function

}

You can call your function by it’s name!

Suppressing some special recognition

There are some characters that have special meaning in the shell programming.(e.g., “>”, “>>”,”>&” etc). If you want to take these kind of character as literal, how would you treat them? Suppose I want to echo this sentence, literally. (“My height > Your Height”). If you try, “echo My height > Your Height”. It wouldn’t work as you want. The program will make a file called “Your Height” and write My Height inside it. There are 3 ways of suppressing special interpretation of shell programming.

  1. Back Slash suppress suppress the special interpretation of an immediate-following character.
  2. Single quotes suppress everything inside them, just except for another single quote.(That is, there is no way to embedded any single quote inside single quotes)
  3. Double quotes suppress most special interpretation. The exception are back quote(i.e., you send a command inside double quotes), back slash(so you can put a double quotes around double qoutes), and dollar sign(so you can still use variables)

Tricky part to think about with quoting

If you quoting something, like “this”, usually most of program thinks it’s one chunk of input when it parse the input. But there is a problem with it in Shell Programming(Darn it, another thing to think? Let’s just click a lot in Window!). Sorry to notice you this. But it’s not that there’s no solution for the problem. So, let’s just take a look at the problem. 

The Problem: Let’s say you have a file name called “file1”, “file2” and “funny file” and you have a program called “prog” that is just “cat” the input file(i.e., print the content of the input files)

If you use $*(this variable stores all inputs), then “funny file” will be problematic. Because any space will be treated as different inputs. So our  program,”prog” will try to find files called “funny” and “”name”

**NOTICE: I’m merely a 2nd year student(= not an expert at all), so the content might be misleading you. So don’t believe 100%. Any correction will be appreciate it. I got many information from everywhere and pictures ,too. However, I’m too lazy to write all the source.

file descriptor and redirection

often there might be some error that we don’t want to show its message but, want to see them later on altogether. So in that case, we can redirect error using 2>

2 is one of file descriptor, and it stands for standard error

0 is standard input which is key board

1 is standard output which is you’re working window

2 is standard error

if you use tyep “command 2> errorlog” then the error wouldn’t be printed out.  Instead of printing error message, it will write the error in the errlog file.

The notion of “>” seems okay. You just got the file descriptor and put “>” before the file or direction that you want to redirect to. However, I felt little bit dizzy, when I saw “>&” ← this bad boy. But he turns out a pretty nice boy inside. So let’s get to know him. >&  is used, when you redirect one file descriptor to another. What I mean by that is for example you directed standard output to some file(output.txt) by typing command 1> output.txt”. Then, later on, you also want to redirect standard  error to the same place that the standard input is redirected.

Then, you type 2>&1, since “&” is meaning “and” we can interpret  in English as “redirect together to the where ever the file descriptor after >& is redirected, please”

—-

I need to study more on “trap”, “double quote and suprresiing some special notation” and “regex”