Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $(command) and `command` in shell programming?

Tags:

bash

shell

sh

ksh

To store the output of a command as a variable in sh/ksh/bash, you can do either

var=$(command) 

or

var=`command` 

What's the difference if any between the two methods?

like image 569
hhafez Avatar asked Jan 16 '11 22:01

hhafez


People also ask

What does $() mean in shell?

$(...) allows command substitution, i.e. allows the output of a command to replace the command itself and can be nested.

What does $() mean in bash?

Dollar sign $ (Variable) The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.

What does #$ mean in bash?

#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments). Follow this answer to receive notifications. edited Jul 9 at 13:55.

What is a command line shell?

A shell is a computer program that presents a command line interface which allows you to control your computer using commands entered with a keyboard instead of controlling graphical user interfaces (GUIs) with a mouse/keyboard/touchscreen combination.


1 Answers

The backticks/gravemarks have been deprecated in favor of $() for command substitution because $() can easily nest within itself as in $(echo foo$(echo bar)). There are other differences such as how backslashes are parsed in the backtick/gravemark version, etc.

See BashFAQ/082 for several reasons to always prefer the $(...) syntax.

Also see the POSIX spec for detailed information on the various differences.

like image 110
SiegeX Avatar answered Oct 14 '22 00:10

SiegeX