Tuesday, May 19, 2020

Linux Shell - What is IFS?

 IFS stands for internal field separator. This is the delimiter used when words are split.

The man page of bash tells :

IFS    The Internal Field Separator that is used for word splitting after expansion and to split lines into
              words with the read builtin command.  The default value is ``<space><tab><newline>''.

The default value of IFS is a space, a tab followed by a newline.
guru@unixschool:~$ echo "$IFS"
  

guru@unixschool:~$ echo "$IFS" | cat -tve
 ^I$
$
guru@unixschool:~$ 
  When we echoed IFS for the first time, we could not see anything becuase they are special characters. On using the tve options of cat, we can see a space, followed by a ^I which is a tab character and then followed by a newline.

Thursday, May 14, 2020

Python - How does an iterator work

 In this article, we will discuss how does an iterator work.  Python has 2 function related to iterator: iter and next. iter creates an iteration object for the requested input, and the next function returns the next element present in the iterator. next keeps on returning till the last element is reached.

   Let us create an iterator for a list and see how the next and iter function works:
>>> l1 = [2,25,33,12]
>>> l1
[2, 25, 33, 12]
>>> it1 = iter(l1)
>>> it1
<list_iterator object at 0x7fc24f93aa58>
>>> next(it1)
2
>>> next(it1)
25
>>> next(it1)
33
>>> next(it1)
12
>>> next(it1)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration
>>> 
When we printed it1, it shows it as an list_iterator object. Everytime next is hit, it gave the next element and finally when there are no more elements, it gives StopIteration.

Tuesday, May 5, 2020

bash - 5 examples to do arithmetic operations

 While working in bash or while writing bash scripts, many times it so happens we rely on external commands to get our math done. Most of the arithmetic can be handled by the bash itself.   In this article, we will see how to do arithmetic operations in bash.

1. Add / Subtract numbers:
     One common way to basic arithmetic using bash is by using the let command.
x=20
y=30
let z=x+y
echo "z is $z"
  This is purely a shell operation without any external command. This way one can do for subtract(/), multiply(*), divide(/) and remainder(%) operation.
x=20
y=30
((z=x+y))
echo "z is $z"
  The other way to do is using the ((expression)) where the expression is an arithmetic one. Using this double brace notation, all the bash arithmetic can be done.
   Bash also allows to use +=, -= operators like in many programming languages. So, if we have something like x=x+10, it can be written as
x=40
((x+=10))
echo "x is $x"