Thursday, February 18, 2016

String concatenation is one of the basic requirements expected from any language. Bash provides various ways to do it. Let us see some of them here.

The most intuitive way to do string concatenation is by writing the strings next to each other.
For example, if the two strings are stored in a variable:

var1="Hello"
var2="World"
var3=$var1$var2
echo $var3

This would print the value of $var3 as:

HelloWorld

Note the lack of space between the two strings that are concatenated.

If you want to print it with space in between, then it has to be changed to:

var1="Hello"
var2="World"
var3="$var1 $var2"
echo $var3

In this case, you need to enclose the RHS of the assignment to var3 in double quote or store it in another variable.

A slightly different way of doing it is by using double quotes around the space alone:

var1="Hello"
var2="World"
var3=$var1" "$var2
echo $var3

If you watch carefully, that shows some interesting behavior. You can concatenate a string stored in a variable and a string literal by just placing one next to the other. This is useful when we have a file name and we want to add something else to name say .bak to say that it is a backup file. Let us try that:

To explain, only the value stored in the second variable was printed. The first variable was ignored. Why?
The culprit is the underscore("_"). Underscore is allowed as a special character in a variable name. So, instead of interpreting $filename as the variable name, the shell will interpret $filename_ as the variable name.
One way to do this is as follows:

Sunday, February 14, 2016

Consider a database storing the details of all schools and students in a city and the information of which student is in which school.

One way to model this is using the following tables:

Schools:

SchoolID

Name

MaxIntake

1

Knowledge School

1200

2

Wisdom School

670

Students:

StudentID

Name

SchoolID

1

Ram

2

2

Peter

1

3

Zaki

2

As is evident from the names, SchoolID in the table Students is a foreign key referring to the primary key SchoolID in the Schools table.

Now, if you want the list of all the students and their schools, the query would be:

select studentid, name, name from schools, students where schoolid = studentid;

But this query will show the same name for both the student and the school. Why?

I will try to explain this without going into the specifics of implementation of the specific DB engine. The part of the query from schools, students where schoolid = studentid will create a temporary table, like this:

SchoolID

Name

MaxIntake

StudentID

Name

SchoolID

2

Wisdom School

670

1

Ram

2

1

Knowledge School

1200

2

Peter

1

2

Wisdom School

670

3

Zaki

2

This table has two fields named as name and when you query the value of name, you get the value from one of them.

To fix this, you need to provide an alias for the table names in the query and use them: