What Does $(Command) & Do?

What Does $(Command) & Do?

I saw the following syntax in a bash script:

 >$(command) &

I know that the ampersand & at the end makes a command run in the background, but I have never seen it in combination with the dollar sign plus the brackets around the command.

What does it do?

3

2 Answers

Short Answer

Given the syntax $(command) &, the result is the same as if you took the output of running just command and then tried to run that as a command. And all of this would be done in the background, meaning that there would be no visible output or hanging in the terminal.

For example, if we had a text file named mycommand.txt with the contents:

echo "Hello World"

Then the command

$(cat mycommand.txt) &

would be equivalent to running

echo "Hello World" &

But since we added the ampersand (&), we wouldn't see any output from this command, so it would be pretty useless in this example.


Long Answer (Explanation)

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. The difference in bash scripting for calling on and declaring variables goes as such:

Declare a variable without the dollar sign and call it with a dollar sign. For example, a script that contains this

#!/bin/bash
STR="Hello World!"
echo $STR

Would output this

Hello World!
Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.