What is the primary purpose of the $ symbol in Unix/Linux shell scripting?

2024

What is the primary purpose of the $ symbol in Unix/Linux shell scripting?

  1. A.

    To terminate a running process

  2. B.

    To access the value of a variable or perform command substitution

  3. C.

    To declare loop variables in Bash

  4. D.

    To redirect output to another file

  5. E.

    To define comments in a shell script

Attempted by 94 students.

Show answer & explanation

Correct answer: B

In Unix/Linux shell scripting, the $ symbol is fundamentally a parameter/variable expansion and command-substitution operator.

Variable access: writing $NAME (or ${NAME}) tells the shell to substitute the value stored in the variable NAME. For example, if greeting="Hello", then echo $greeting prints Hello. Special parameters such as $0 (script name), $1 $2 ... (positional arguments), $? (exit status of the last command), $$ (current process ID) and $# (argument count) are all read with $.

Command substitution: $(command) (or the older backtick form) runs command in a subshell and substitutes its standard output in place. For example, today=$(date) stores the output of date in the variable today. The related $(( ... )) form performs arithmetic expansion.

Therefore the primary purpose of $ is to access the value of a variable or to perform command substitution, making option 2 correct. Process termination is done with the kill command, output redirection with > / >>, and comments with #, so none of those rely on $.

Explore the full course: Niacl Ao It Specialist