Substitution

From LQWiki
Jump to navigation Jump to search

This article is a stub and needs to be finished. Plunge forward and help it grow!

Substitution is a feature of the bash shell that allows you:

Storing output to variables

Imagine you got that little command line from bash_tips that outputs your IP-address:

duffman:~ # ifconfig eth1 | sed -rn 's/^.*inet addr:([^ ]+).*$/\1/p'
192.168.0.6

Now, you want your IP address stored into a variable, say, you want to substitute the commandline by its output and store it to a variable. Use the operator $() to do this:

duffman:~ # ip=$(ifconfig eth1 | sed -rn 's/^.*inet addr:([^ ]+).*$/\1/p' )
duffman:~ # echo $ip
192.168.0.6
duffman:~ #         

The operator $() executes the statement that is within its paranthesis and substitutes itself with the output of that statement. The operator ´´ (backticks) do the same, but they are not cascadable.

Getting a list of files

The operator * is substituted by all files in your current folder, e.g.

ls *

behaves the same as

ls file1 file2 file3

See also