0

What is the difference in collect a command output in Shell script using `command` and $(command)? For example:

# IP1=$(ifconfig eth0 | grep -e "inet " | cut -d: -f2 | awk '{print $1}')
# IP2=`ifconfig eth0 | grep -e "inet " | cut -d: -f2 | awk '{print $1}'`
# echo $IP1 $IP2
> 192.241.145.112 192.241.145.112
1
  • Sidenote: your triple pipe seems a bit useless, why no |awk -F: '/inet/{print $2}'
    – Bernhard
    Commented Dec 7, 2013 at 18:32

2 Answers 2

3

The main difference is that backticks don't nest: You cannot embed one backticked command inside another. (Actually you can, but you need to backslash-escape them, and it gets hairier from there on.) That was, I believe, the main motivation for coming up with the newer syntax $(command).

The $(command) syntax also provides a convenient shortcut for interpolating the contents of a file: $(<filename) is equivalent to $(cat filename).

Another difference: $() is not supported by some common shells.

4
  • 2
    You can nest backticks with any (Bourne syntax) shell, not just bash. $( ) is not a bash extension, it is a standard syntax supported by all POSIX conforming shells and some non conforming ones.
    – jlliagre
    Commented Dec 7, 2013 at 17:27
  • @jlliagre, thanks for the correction. Are you sure about the POSIX part? I checked before posting, and my tcsh does not support it. Perhaps it's not POSIX compliant (I haven't checked), but this means that you don't have to go exotic or ancient to run into problems.
    – alexis
    Commented Dec 7, 2013 at 17:40
  • 1
    I'm more than sure about the POSIX part. It's no surprise tcsh doen't support it. tcsh is absolutely not a bourne compatible shell but a csh one and has zero POSIX conformance.
    – jlliagre
    Commented Dec 7, 2013 at 18:08
  • I see, thanks. I didn't know that the csh line is outside the POSIX pale.
    – alexis
    Commented Dec 7, 2013 at 18:10
1

The command substitution $( ) syntax was introduced around 25 years ago by ksh to overcome the limitations of the original " `command` " one, especially the complex way to achieve command nesting.

It was included by the POSIX shell standard and by other shells aiming standard conformance like bash.

The old syntax was supported in ksh88 only to provide compatibility with legacy scripts. There was a hope for it become obsolete but unfortunately, the "new" syntax is still not enough advertised or taught and the legacy syntax is still too much used and popular.

Not the answer you're looking for? Browse other questions tagged .