Get variable type in bash

Question:

In Python I can get variable type by:

>>> i = 123
>>> type(i)
<type 'int'>

I saw on this page that there are no variable types in bash. The explanation given is:

Untyped variables are both a blessing and a curse. They permit more flexibility in scripting and make it easier to grind out lines of code (and give you enough rope to hang yourself!). However, they likewise permit subtle errors to creep in and encourage sloppy programming habits.

But I’m not sure what it means and what are the real advantages (and drawbacks).

Asked By: tlorin

||

Answers:

Bash doesn’t have types in the same way as Python (although I would say that Python has classes rather than types). But bash variables do have attributes that are given (mostly) through declare, but the range of attributes is fairly small. You can find an attribute using declare -p, for example, declare -i creates an integer:

declare -i num
num=42
declare -p num

Gives:

declare -i num="42"

But this is a poor feature compared to Python, or almost any modern language. The problem is that in something like Bash the basic type is a text string, and that’s fine if all you need is text strings for things like filenames. But once you start needing to do heavy processing you need other types. Bash doesn’t support floating point, for example. You also need compound types, like a class describing a file with all the attributes that a file can have.

Bash 4 does have associative arrays (declare -A), similar to Python dictionaries, which extends functionality considerably.

Even so, most would agree that Object Orientation is pretty much impossible in Bash, although some would argue that it can be done in Korn shell (which has much more powerful features). http://en.wikipedia.org/wiki/Object-oriented_programming

What bash has is fine for what it is meant for – simple processing that is quick and easy to get working. But there is a critical mass beyond which using such a language becomes unwieldy, error prone, and slow. That critical mass can be one of scale, i.e. large amount of data, or complexity.

There is no simple cut-off point where you should stop using Bash and switch to Python. Its just that as programs get more complex and larger the case for using Python gets stronger.

I should add that shell scripts rarely get smaller and less complex over time!

Answered By: cdarke
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.