Bash Special Variables


To better understand the bash special variables, I wrote a script to help myself.

#!/bin/bash

#Usage of $#
echo ————————————————————
echo -e You have entered $# arguments.

#Usage of $*
echo ————————————————————
export IFS=’-‘
echo -e The arguments are: “$*” \(seperated by -\)

#Usage of $@
echo ————————————————————
n=1
for arg in “$@”
do
        echo -e The $n argument is: “$arg”
        let n+=1
done

#Usage of $$
echo ————————————————————
echo This shell process ID is $$
ps aux | grep $$

#Usage of $!
echo ————————————————————
ping -c 20 127.0.0.1 > /dev/null 2>&1 &
echo -e The most recently executed backgroup process ID is $!
ps aux | grep ping

#Usage of $?
echo ————————————————————
ping -c 1 nowhere > /dev/null 2>&1
echo the exit code of \”ping -c 4 nowhere\” is $?
ping -c 1 127.0.0.1 > /dev/null 2>&1
echo the exit code of \”ping -c 4 127.0.01\” is $?

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s