Thursday, January 22, 2009

Bash Command Substitution











Bash Command Substitution (and double substitution)

In bash, you can do some interesting things like using the output of a command inside of another command.  Once common area I use this a lot is creating some kind of file with the host name in the file itself.  Let's say you are going to compare password files from a couple of different server or something.  You can copy the file and have it named uniquely in one command.  This is useful because you can use the one command on multiple ssh sessions.  It's just a simple paste action with the middle mouse. The command would look like this:

scp /etc/passwd someserver:/repo/`hostname`.passwd

Another case might be dates.  The same example as above but with the date command might look like this:

scp /etc/passwd someserver:/backups/`hostname`.`date +%Y%m%d`.passwd

Now you have dated copies of the file you want for each server.  The problem I had was that I needed to use the IP address of the server in the file name.  While...

scp /etc/passwd someserver:/backups/`host `hostname``.passwd

might make sense, it doesn't work.  The solution I found was to declare a variable at the begining of the command.  So the answer looks like...

foo=`hostname`; scp /etc/passwd someserver:/backups/`host $foo |awk '{print $4}';`.passwd

I thought I'd throw that out there if anyone else need a double command substitution in bash.


1 comments:

Indie said...

Why not just assign the IP to foo?

foo=$(hostname | xargs host -t A | cut -f4 -d\ )
scp /etc/passwd someserver:/backups/$foo.passwd