When should one use $( ) in defining variables

Some shell scripts I have come across use the following syntax when defining variables:

file_list_1=$(echo "list.txt")

or

file_list_2=$(find ./)

I would have used:

file_list_1="list.txt"

and

file_list_2=`find ./`

I’m not sure which if any of the above are better or safer. What is the benefit of using the syntax x=$( ) when setting a variable?

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

From the manual (man bash):

$(command)  or  `command`

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.
The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or .
The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

The POSIX standard defines the $() form of command substitution. $()
allows nested commands and looks better (legibility). It should be available on all Bourne shells.

You can read more on IEEE Std 1003.1, Shell Command Language, Section 2.6.3 Command Substitution.

At least one Unix, AIX, has documented that backticks are obsolete. From that link:

Although the backquote syntax is accepted by ksh, it is considered obsolete by the X/Open Portability Guide Issue 4 and POSIX standards. These standards recommend that portable applications use the $(command) syntax.

However, /bin/sh does not have to be POSIX compliant. So there is still sometimes a case for backticks in the real world, as @Jeight points out.

Method 2

It’s a lot of personal preference. Using a backtick to signify a command would be more POSIX compatible with older systems. The $() is more modern and is easier to read for some people. I would personally never use file_list_1=$(echo "list.txt"). It seems to ugly and has no additional use.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x