*NIX Tricks

[perl] Access shell environmental variables in your Perl script

Posted in perl by kousik on August 26, 2011

The environmental variables are stored in %ENV hash (“associative array”). Now if you want to access a shell variable, say $HOME, in your Perl script, then you need to refer to it as $ENV{'HOME'}:

#!/usr/bin/perl
$my_home_dir = "$ENV{'HOME'}" ;
$my_shell = "$ENV{'SHELL'}" ;
$my_editor = "$ENV{'EDITOR'}" ;

Don’t forget the curly braces and the single quotes!

Reference: Devdaily blog.

[cli] Selectively break a string into pieces and display in new lines

Posted in cli, unix by kousik on January 14, 2010

Display each different part of a string separated by a character, say colon (:), in new lines:

Using echo:
$ echo -e ${PATH//:/\\n}

Using printf:
$ printf "%s\n" ${PATH//:/\/* }

Here we chose the system $PATH variable whose different parts are separated by colons.

Credit: Command-line-fu

[awk] Command line calculator using awk

Posted in awk, cli, linux, osx, unix by kousik on November 3, 2009

This is an update on our bash command line calculator posted a few days ago — except for the fact that this time we’ll use awk to do the calculation instead of bc. As I mentioned in that post, you may use python or ruby (irb) to do the same thing, but these tricks may be useful if you don’t  have ruby or python installed (bc and awk, in general, come by default in any Unix or GNU/Linux distro).

First, create (or rewrite if you used our last trick) function “?”  as follows and put it in your ~/.bashrc file:

? () { awk "BEGIN{ print $* }" ;}

and make sure to reload your ~/.bashrc file (do the similar thing if you're using any other shell). [NOTE: ZSH does not like ``?'' as a function, so you might consider replacing it with something reasonable, e.g., ``compute'']

Now, if you want to calculate an expression, do it, for example, as

$ ? "2*3+4.0*(9.9+8.1)"

and don’t forget the quotes.

.

The advantage of this over bc is that you can use more arithmetic and trigonometric functions (link):

              atan2(y,x)     Arctan of y/x between -pi and pi.

	      cos(x)	     Cosine function, x in radians.

	      exp(x)	     Exponential function.

	      int(x)	     Returns x truncated towards zero.

	      log(x)	     Natural logarithm.

	      rand()	     Returns a random number between zero and one.

	      sin(x)	     Sine function, x in radians.

	      sqrt(x)	     Returns square root of x.

.
You may include variables as well in the function definition itself:

? () { awk "BEGIN{ pi = 4.0*atan2(1.0,1.0); degree = pi/180.0; print $* }" ;}

where we have defined the variable pi and degree (such that tan(pi/4.0) = 1.0 and pi radians is equivalent to 180 degrees) to be used later, e.g.

$ ? "cos(pi)"
$ ? "cos(90*degree)"

and I’m sure that you’ll get -1 and 0 (within the machine precision), respectively, as the answer!

(You may find some more interesting calculator related tricks posted in this blog scattered in different pages)

Credit: here and here (via LifeHacker).

UPDATE: I just realized that I can use the calc package (besides bc, awk, python and irb) to do the command line math wizardry more efficiently (and let’s take that as the end to this command line calculator series!). It has a larger set of built-in functions. You may grab the source code from the maintainer’s website and follow my instructions to install it on your system [although binaries are also readily available, e.g. apcalc package for Ubuntu 9.10 (Karmic Koala)].

[bash] Introductory BASH scripting for scientists

Posted in bash by kousik on September 28, 2009

These are based on the type of work I am interested in, i.e. scientific programming: you won’t see much about character strings in this post since we are mostly interested in numbers!

These can all be directly typed in the BASH prompt. Semicolons basically indicate the start of a new statement: you may put them in separate lines; and in that case, do not put the semicolon between the statements typed in different lines. The dollar sign ($) at the beginning of the command line indicates the command prompt and it is not a part of the command!

1. The basic
Print the sum of two integers:

$ echo $((2+3))
The two pairs of parentheses interpret them as numbers. You can also use square brackets (just a single pair):

$ echo $[2+3].

For floating point numbers use bc.

Variable substitutions may be done as
$ num1=10; num2=20; echo $(($num1+$num2))
(no space between the equality sign and the variable/number)

2. Conditional block: arithmetic conditional operators are eq, lt, le, gt and ge:

$ i=10; j=20; if [ $i -lt $j ]; then echo "$i<$j? True"; fi
$ i=$RANDOM;j=$RANDOM; if [ $i -lt $j ]; then echo "i=$i is less than j=$j"; else echo "i=$i is NOT less than j=$j";fi
($RANDOM equals a random number at each invocation)

Notice the  spaces between the square brackets and the expression within it.

3. Array:
Assignment:

$ arr=(10 11 12)
which is the same as

$ arr[0]=10; arr[1]=11; arr[2]=12

Following constructs show how you can actually access the array (link)

$ echo ${arr[2]}  # The 3rd element of the array
$ echo ${arr[*]}  # All of the items in the array
$ echo ${!arr[*]} # All of the indexes in the array
$ echo ${#arr[*]} # Number of items in the array
$ echo ${#arr[0]} # Length of item zero

4. For loop

$ for (( c=1; c<=5; c++ )); do echo "c = $c"; done            # C-style
$ for c in 1 2 3 4 5; do echo "c = $c"; done                  # List
$ arr=(1 2 3 4 5); for c in ${arr[*]}; do echo "c = $c"; done # Explicit array
$ for c in {1..5}; do echo "c = $c"; done                     # 1 thru' 5 with unit intervals
$ for c in {0..10..2}; do echo "c = $c"; done                 # 0 thru' 10 with interval=2

5. While and until loops
$ c=0; while [ $c -lt 10 ]; do echo "c = $c"; let c++; done
You may replace “let c++” by “((c++))”.

$ c=20; until [ $c -lt 10 ]; do echo "c = $c"; let c--; done

6. User input
Use read command to read in user input, e.g.
$ echo "Enter two integers"; read num1 num2; echo "$num1+$num2=$((num1+num2))"
In the second echo statement, when num1 and num2 are not enclosed within two pairs of parentheses they are treated as character strings, whereas in the last part the double parentheses cause them to be treated as numbers.

N.B. For the above loops and blocks, a line break between do or then and the statement that immediately follows it is allowed.

Reference: link.

Follow

Get every new post delivered to your Inbox.