LinuxCommandLibrary

$

Execute a command as a user

TLDR

Print a variable

$ echo $[VARIABLE]
copy

Run variable contents as a command
$ $[VARIABLE]
copy

Print the exit status of the previous command
$ echo $?
copy

Print a random number between 0 and 32767
$ echo $RANDOM
copy

Print one of the prompt strings
$ echo $[PS0|PS1|PS2|PS3|PS4]
copy

Expand with the output of command and run it. Same as enclosing command in backticks
$ $([command])
copy

List how many arguments the current context has
$ echo $#
copy

Print out a Bash array
$ echo $[{array_name[@]]}
copy

SYNOPSIS

$VAR or ${VAR} for expansion; $n positional; $? special; $(cmd) substitution; $((expr)) arithmetic.

PARAMETERS

$0
    Name of the current shell or script

$n (n=1-9)
    Positional arguments (use ${n} for n>9)

$*
    All positional parameters as single string

$@
    All positional parameters as separate words

$#
    Number of positional parameters

$?
    Exit status of last command (0=success)

$$
    Process ID of the current shell

$!
    Process ID of last background job

$PPID
    Parent process ID

DESCRIPTION

The $ symbol in Linux shells (like Bash) serves multiple critical roles.

First, it denotes the secondary prompt in interactive shells: $ for non-root users and # for root, customizable via the PS1 variable (e.g., PS1='\u@\h:\w\$ ').

Primarily, $ enables variable expansion: prefix a variable name to retrieve its value, as in echo $PATH or echo ${USER} for safer parsing. In double quotes, it expands; in single quotes, it's literal.

It also denotes positional parameters ($1, $2, etc.) and special parameters like $? (exit status), $$ (PID), providing essential scripting feedback.

Additionally, $() performs command substitution (ls $(pwd)), and $(( )) enables arithmetic expansion (echo $((2+3))). These features, inherited from Bourne shell, make $ indispensable for dynamic scripts and automation.

CAVEATS

Expansion suppressed in single quotes; undefined vars expand to empty string (use ${VAR:-default}); quote to prevent word-splitting/glob expansion.
Array indices use ${ARRAY[0]}.

PROMPT CUSTOMIZATION

Set PS1 for prompt: PS1='\$? \w\$ ' shows exit code and path ending in $.

COMMAND SUBSTITUTION

Prefer $(ls) over `ls` for nesting and readability.

ARITHMETIC

$((expression)) for math; supports + - * / %.

HISTORY

Introduced in Bourne Shell (1977); expanded in Bash (1989) with $( ) and ${} brace syntax for portability over backticks.

SEE ALSO

bash(1), sh(1), dash(1), env(1), printf(1)

Copied to clipboard