Showing posts with label unix. Show all posts
Showing posts with label unix. Show all posts

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!

Tuesday, November 16, 2010

"which" command wasn't working in Linux

That was weird, or is that how it works?

I had this executable "db_linux" in "/usr/local/bin" and this was included in the env variable PATH. But there was no execute permission for this executable.And when I did a "which db_linux", it didn't show me anything. I was checking the file, the path everything was proper. The I thought fine lets execute it with absolute path. In the process I gave execute permission for the file and executed it. Later when I tried "which db_linux" again, it was showing. May be that is how it works.

BTW, I use Fedora Core 13 v 2.6.33.3

Code:
[root@ahamed bin]# ls -lrt
total 4
-rw-r--r--. 1 root root 63 Nov 16 16:33 db_linux

[root@ahamed bin]# which db_linux
/usr/bin/which: no db_linux in (/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:
/usr/loca/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)

[root@ahamed bin]# chmod 744 db_linux
[root@ahamed bin]# ls -lrt
total 4
-rwxr--r--. 1 root root 63 Nov 16 16:33 db_linux

[root@ahamed bin]# which db_linux
/usr/local/bin/db_linux

Have a good day!