29

What is $() in Linux Shell Commands?

For example:

chmod 777 $(pwd)
1
  • 1
    Note that there's no such thing as the line shell command. There are a number of shell applications available for Linux. Jul 30, 2014 at 12:44

3 Answers 3

34

It's very similar to the backticks ``.

It's called command substitution (posix specification) and it invokes a subshell. The command in the braces of $() or between the backticks (`…`) is executed in a subshell and the output is then placed in the original command.

Unlike backticks, the $(...) form can be nested. So you can use command substitution inside another substitution.

There are also differences in escaping characters within the substitution. I prefer the $(...) form.

8
  • 6
    backticks can be nested as well. Note that trailing newline characters are removed from the output of the command. Jul 30, 2014 at 12:50
  • 2
    @StéphaneChazelas how can backticks be nested? You mean by ecxessive escaping?
    – chaos
    Jul 30, 2014 at 12:53
  • 3
    Yes: like with echo `echo \`echo foo\`` bar Jul 30, 2014 at 12:59
  • 2
    Any official reference saying that backticks are deprecated?
    – vinc17
    Jul 30, 2014 at 13:08
  • 1
    Found this answer: unix.stackexchange.com/questions/126927/… seems they are not deprecated. Changed my answer, thanks
    – chaos
    Jul 30, 2014 at 13:17
5

In POSIX or POSIX-like shells (ksh, bash, ash, zsh, yash...), it is like ``: the command inside $() is executed and replaced by its standard output. Word-splitting and filename generation are done unless $() is inside double-quotes. Thus

chmod 777 $(pwd)

should be replaced with:

chmod 777 "$(pwd)"

to avoid word-splitting and filename generation on the current working directory path.

Or even better (except under some shells, like zsh, in case the directory has been renamed):

chmod 777 "$PWD"

Since $PWD is a special variable that holds the path to the current working directory in POSIX shells.

Or even better:

chmod 777 .

Since the . entry in the current directory is a hard link to that directory itself.

0
3

This $() is used for executing a command mostly inside some other command.

chmod 777 $(pwd)

pwd command gives the current working directory. So, when the whole thing is executed output of pwd will replace its position and serve as the argument to chmod , and the result is that all your present working directory get the permission 777 which I guess should never be used in production environment ;) .

You must log in to answer this question.

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