The dollar sign in *nix


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.

command.sh

#!/usr/bin/env bash

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

Run command.sh as follows:

$ ./command.sh dollar sign

Its result:

./command.sh
dollar
sign
2

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 command.sh a little bit

#!/usr/bin/env bash

# Set IFS to see the difference
IFS='-' 

echo $@
echo $*
echo "$@"
echo "$*"
$ ./command.sh dollar sign
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 "$@"
do
    echo $arg
done
$ ./command.sh dollar sign
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
background
[1]+  Done  echo "background"
$ echo $!
16422

$$ - The process ID of the current shell.

$ echo $$
15699

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.


Comments