Skip to content
Fetching contributors…
Cannot retrieve contributors at this time
138 lines (104 sloc) 3.08 KB
title path date tags
The dollar sign in *nix
TL;DR, Linux, Unix, Bash

I wrote this post to use it when I forget the usage of $ sign. And, I think it would be useful for beginners like me, too.

Also, this is the first post of the TL;DR series. I am planning to have less writing and more coding in posts of this series. And, I hope this one won't be the last.

Let's get started.

First things first: Positional Parameters

  • $1, $2 $3, ... are the positional parameters that are assigned from the shell's arguments.
  • $0 is the name of the shell script.
  • $# is the number of positional parameters.

Let's have a quick example of these.

#!/usr/bin/env bash

echo $0
echo $1
echo $2
echo $#

Run as follows:

$ ./ dollar sign

Its result:


All the positional parameters

  • $@ and $* expand to the positional parameters, starting from one.
  • "$@" is an array-like construct of all the positional parameters, [$1, $2, $3, ...]
  • "$*" is the IFS expansion of all the positional parameters, $1 $2 $3, ...
  • $IFS, internal field separator, is used for word splitting. The default value of $IFS is <space><tab><newline>, and may be changed.

Let's change a little bit

#!/usr/bin/env bash

# Set IFS to see the difference

echo $@
echo $*
echo "$@"
echo "$*"
$ ./ dollar sign
dollar sign
dollar sign
dollar sign

Iterate over the arguments

As I mentioned above, "$@" is an array-like construct. We can iterate over the arguments using it.

for arg in "$@"
    echo $arg
$ ./ dollar sign

More $

$? - The exit status of the most recent foreground command (pipeline).

$ non-existing-command
$ echo $?
127 # which means "command not found"

$! - The process ID of the most recent background command executed from the current shell.

$ echo "background" &
[1] 16422
[1]+  Done  echo "background"
$ echo $!

$$ - The process ID of the current shell.

$ echo $$

You can find all examples in this post on GitHub Gist.

Your comments and suggestions are welcome. Also, you can edit this page on GitHub.

You can’t perform that action at this time.