Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What is $() in Linux Shell Commands?

For example:

chmod 777 $(pwd)
share|improve this question
1  
Note that there's no such thing as the line shell command. There are a number of shell applications available for Linux. –  Stéphane Chazelas Jul 30 at 12:44

3 Answers 3

up vote 2 down vote accepted

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 beween the backticks (``) is executed in a subshell and the output is then placed in the original command.

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

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

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

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.

share|improve this answer

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 ;) .

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.