Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Sunday, March 18, 2012

echo $SHELL and echo $0

"How do you identify your current shell?" is one of the frequently asked interview question.


Some would say "echo $SHELL" and some would say "echo $0". So, which is the right answer?


See for yourself!
root > grep ^root /etc/passwd
root:x:0:0:root:/root:/bin/bash

root > bash
root > echo $SHELL
/bin/bash
root > echo $0
-bash

root > ksh
root > echo $SHELL
/bin/bash
root > echo $0
ksh
Got it?


$SHELL will always print the login shell. $0 will print the current shell.


Good Day!

Tuesday, January 3, 2012

Command Substitution in Linux

In Linux, we do a lot of onliners on the shell. Something like,

Code:
root@bt > date
Tue Jan  3 01:19:19 IST 2012

Now if we want to store this date into a variable, what do we do?
There are 2 ways in which we can achieve this i.e. command substitution

One way, using backticks i.e. `

Code:
root@bt > var=`date`
root@bt > echo $var
Tue Jan 3 01:20:47 IST 2012

Other way is using $(...)

Code:
root@bt > var=$(date)
root@bt > echo $var
Tue Jan 3 01:21:18 IST 2012

Command line or script, you can use it anywhere you want. I prefer the second way!

Note, there is no space between var = and the command. Why so? Because that is how it should be.
That is the syntax. If you have a space in between you will see strange errors.
Let us try it once with a space inbetween,

Code:
root@bt > var =$(date)
No command 'var' found, did you mean:
 Command 'jar' from package 'openjdk-6-jdk' (main)
 ...
 Command 'par' from package 'par' (universe)
var: command not found

Oops, we don't want that now, do we?

Good Day!