Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash for inline command

Tags:

bash

command

I have to run commands, in a bash script, and within this bash script I have to run other commands. I am running CentOS.

I found 2 ways to do this on blogs and manuals:

1) using the ticks or accent char

command `sub command` 

or

2) using the dollar sign and parentheses

command $(sub command) 

What is the difference between the 2 and which one is preferable to use?

like image 320
dale Avatar asked Dec 29 '11 03:12

dale


People also ask

How do you write on one line in bash?

Bash for loop in one line is a control structure that allows you to repeat a certain set of commands multiple times. The syntax of bash for loop in one line is: for i in (list); do command1; command2; done.

How do I run a bash script from the command line?

In order to run a Bash script on your system, you have to use the “bash” command and specify the script name that you want to execute, with optional arguments. Alternatively, you can use “sh” if your distribution has the sh utility installed. As an example, let's say that you want to run a Bash script named “script”.

How do you write a for loop in Linux terminal?

The basic syntax of a for loop is: for <variable name> in <a list of items>;do <some command> $<variable name>;done; The variable name will be the variable you specify in the do section and will contain the item in the loop that you're on.

What is command substitution in bash?

Command substitution in Bash allows us to execute a command and substitute it with its standard output. Note this command executes within a subshell, which means it has its own environment and so it will not affect the parent shell's environment.


2 Answers

There's no difference except in "nestability":

The $() is nestable:

$ echo $(echo "hi" $(echo "there")) 

while the `` is not.

like image 90
holygeek Avatar answered Oct 14 '22 15:10

holygeek


Others have pointed out the difference in syntax (basically, $() is slightly cleaner wrt nesting and escapes), but nobody's mentioned what I consider the more important difference: $() is much easier to read. It doesn't look like single-quotes (which mean something totally different), and the opening and closing delimiters are different, making it easier to visually distinguish its contents.

For your own scripts, this may not be really critical; code readability is good, but functionality is more important. But for anyone writing tutorials, sample code, stackoverflow answers, etc, readability is much more important. People will type single-quotes instead of backquotes when typing in examples, etc, and then get confused when it doesn't work as expected.

So for everyone writing examples on stackoverflow: please save your readers some trouble, and always use the $() form.

like image 28
Gordon Davisson Avatar answered Oct 14 '22 15:10

Gordon Davisson