The dollar sign in *nix
TL;DR, Linux, Unix, Bash
I wrote this post to use it when I forget the usage of
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.
$0is 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 $#
command.sh as follows:
$ ./command.sh dollar sign
./command.sh dollar sign 2
All the positional parameters
$*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
<space><tab><newline>, and may be changed.
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
$? - 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" &  16422 background + 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.