What is $() in Linux Shell Commands?
For example:
chmod 777 $(pwd)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 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 😉 .
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0