jonathan lam
jonathan lam

Reputation: 55

Unix Shell - Understanding the use of parenthesis for variables

I am new to Unix Shell scripting and I am kind of confused about in what cases do I have to use these type of parenthesis. Assume that abc is a variable consisting of a string. Can someone give me examples of how to use these parenthesis and when I should use them?

abc $abc ${abc} $(abc) ($abc)

Upvotes: 4

Views: 2708

Answers (2)

sashang
sashang

Reputation: 12234

The $ character is used to signal that parameter expansion is to be performed on the term following. Therefore if the shell reads

abc

on it will be parsed as a command and the shell will try and execute that command.

If the shell sees

$abc

it will perform parameter expansion on the text abc and effectively substitute the value of abc in place.

${abc}

will also perform parameter expansion. The use of the parentheses becomes significant when you have expressions like this:

${abc}_sometext

versus

$abc_sometext

In the 1st instance the shell will perform parameter expansion on abc. In the second instance it will perform parameter expansion on abc_sometext

The $( tells the shell to execute whats in the braces and perform command substitution. In this context the $ is not used for parameter expansion. So if the shell reads the following:

$(abc)

the shell will execute abc and the output from it will be substitued in place and the shell will try to execute that string.

( simply groups commands and executes them in a subshell. So

(abc)

will execute abc but unlike $(abc) it will not try and execute whatever the output of the command is. For example:

$ $(which ls)
Desktop  Documents  Downloads  Mail  Manjaro  Music  Pictures  Public      Templates  Videos  bin  code  tmp
$ (which ls)
/usr/bin/ls
$ 

Upvotes: 7

Andrew White
Andrew White

Reputation: 53516

This is rather crude but should be a good start:

abc - bare word\string that can be a variable name: abc=123

$abc - reference to a variable called abc

${abc} - string safe variable reference file_${abc}_name.txt

$(abc) - run the command abc and use it's stdout in place of the $(abc)

($abc) - run the command stored $abc in a subshell

Assuming you are in bash read the docs on variables and command substitution and parameter substitution.

Upvotes: 9

Related Questions