Get variable type in bash

In Python, I can get the type of a variable:

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

I saw on this page that there are no type variables in bash. Explanation given:

Untyped variables are both a blessing and a curse. They provide greater flexibility in scripting and simplify shredding lines of code (and give you enough rope to hang yourself!). However, they also allow subtle bugs to creep in and encourage sloppy programming habits.

But I'm not sure what that means and what are the real advantages (and disadvantages).

Thank you for your responses!:)

+6
source share
1 answer

Bash has no types just like Python (although I would say that Python has classes, not types). But bash variables have attributes that are given (mostly) through declare , but the range of attributes is pretty small. You can find the attribute with 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 bad feature compared to Python or almost any modern language. The problem is, in something like bash, the base type is a text string, and that is fine if all you need is text strings for things like file names. But once you start doing heavy processing, you need other types. bash, for example, does not support floating point. You also need complex types, such as a class that describes a file with all the attributes that a file can have.

Bash 4 has associative arrays ( declare -A ), similar to Python dictionaries, which greatly expand the functionality.

However, most will agree that Object Orientation is almost impossible in Bash, although some argue that this can be done in the Korn shell (which has much more powerful features). http://en.wikipedia.org/wiki/Object-oriented_programming

What bash is is great for being designed for simple processing that works quickly and easily. But there is a critical mass beyond which the use of such a language becomes cumbersome, error prone and slow. This critical mass can be one of the scales, that is, a large amount of data or complexity.

There is no simple clipping point where you should stop using bash and switch to Python. Its just that as programs become more complex and larger, the point of using Python becomes stronger.

I must add that shell scripts rarely become smaller and less complex over time.

+9
source

Source: https://habr.com/ru/post/985842/


All Articles