What is $()
in Linux Shell Commands?
For example:
chmod 777 $(pwd)
What is $()
in Linux Shell Commands?
For example:
chmod 777 $(pwd)
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.
yash
does have trouble with the Bourne/Korn syntax it would seem. And POSIX leaves the behaviour mostly unspecified when nesting with quotes.
– Stéphane Chazelas
Jul 31 '14 at 09:08
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.
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 ;) .