Work the Shell - Special Variables I: the Basics
There I was, trying to come up with a topic for this column, when I did what I usually do when stumped: I sent a question out to my Twitter followers. This time, I got a great answer, from John Minnihan: “How about how special vars inside a script, for example, #!/bin/bash script="${0##*/}" current=`dirname "$0"` cd $current; make?”
That's a good topic, so let's dig into it, starting with the basics this month, shall we?
The basic notation of variables in the shell is $varname, but I bet you've already used a few special notations without really thinking about it. For example, want to know how many positional parameters (aka starting arguments) you received when the script was invoked? Using $# gives you the value:
echo "you gave me $# parameters"
Want to get a specific positional parameter from the starting command line? That's done with other special variables: $1, $2, $3 and so on. These are rather odd cases actually, and the shift command shifts them all down one, so you easily can parse and trim command flags.
Try this snippet to see what I'm talking about:
echo "arg1 = $1" ; shift ; echo "now arg1 = $1"
The variable $0 is a special one in this sequence. It's the name of the script or program invoked. This can be quite helpful, because it means you can add multiple commands to your Linux shell with a single shared script base.
Let's say that you want to add “happy” and “sad” as two new command-line options, but you want to do it within a single script. Easy! Write the script, save as “happy”, create a symbolic link that means “sad” points to “happy”, and put this in the script itself:
if [ "$0" = "happy" ] ; then echo "I am so darn happy too, hurray!" else echo "Sorry you're sad. Why not take a walk?" fi
See how that works? It turns out that there's a nuance to this usage, however, because you often get the full path in the $0 variable, so most people use $(basename $0) instead of just utilizing the $0 directly.
Another special variable that you might have encountered is the status variable, $?. In a script, this contains the return value of the most recently executed (external) command.
This is where you need to read man pages so you know what to expect on success and failure, but as an example, consider the test command. According to the man page, “if [the expression] evaluates to true, it returns a zero (true) exit status; otherwise it returns 1 (false). If there is no expression, test also returns 1 (false).”
This means you could do this:
test 1 --eq 3 if $? ; then
Quick, now, would we be within this conditional statement or not? That's where it's tricky because zero = true and nonzero = false, which is somehow opposite to how we naturally think of conditional tests (well, how I think of them, at least). In fact, the above test would be testing 1, because the “test” would evaluate to false, and its return value also would be false.
Now, using test like this is a sort of daft example, but what if you wanted to create a subdirectory and then test to see if it was successful? That's a perfect use for $?, actually:
mkdir $newdir if [ $? --ne 0 ] ; then echo "We failed to make the directory $newdir"
It turns out that you also can streamline this sort of thing by having the “if” directly evaluate the return code:
if mkdir $newdir ; then
That's a better coding style, although it can be confusing if you are used to having conditional expressions be value tests, not actually commands that do something.
A special variable that I use with great frequency for helping create temporary file names is $$, which expands to the current process ID in the system. For example:
$ echo $$ 3243
If you're doing a lot with subshells or spawning subcommands, another useful variable is $!, which is the process ID of the most recently spawned background command. I've never used this in any of my shell scripts, but you might find a situation where it's helpful.
The last example I'll talk about here is most useful when you want to hand starting parameters to subshells. The two options are $* and $@, and it's so convoluted to explain the difference that it's easier just to demonstrate.
Let's start with a tiny script that simply reports how many parameters it's given:
#!/bin/sh echo "I was given $# parameters" exit 0
I'll call that subshellcount.sh and utilize it like this:
#!/bin/sh echo "you gave me $# variables and the first is $1" echo "unprotected parameters:" ./subshellcount.sh $1 $2 $3 $4 echo "or, more succinctly:" ./subshellcount.sh $* echo "but when we put \$* in quotes:" ./subshellcount.sh "$*" echo "by comparison, same thing with \$@:" ./subshellcount.sh "$@"
Watch what happens when I invoke it with three parameters, one of which has a space embedded:
$ sh test.sh I love "Linux Journal" you gave me 3 variables and the first is I unprotected parameters: I was given 4 parameters or, more succinctly: I was given 4 parameters but when we put $* in quotes: I was given 1 parameters by comparison, same thing with $@: I was given 3 parameters
Can you see the difference here? When we don't take efforts to protect the space in the third positional parameter (either by just referencing $3 or using the $@ without quotes), it splits into two parameters to the subshell, and we get a count of four.
Quoting by itself doesn't do the trick either, because of the difference between $@ and $*. With the latter, everything expands without “breaking out of” the quotes, so $* ends up being a single positional parameter to the subshell. Fortunately, $@ works exactly as we'd like, and the subshell gets three parameters, not one, not four.
It seems a bit trivial, but when you start working with filenames that have spaces in them, for example, you quickly will learn just how tricky it is to get all of this correct!
I'm going to stop here, and starting next month, we'll delve into the more obscure and complex shell variable notation. It's interesting stuff.
Dave Taylor is a 26-year veteran of UNIX, creator of The Elm Mail System, and most recently author of both the best-selling Wicked Cool Shell Scripts and Teach Yourself Unix in 24 Hours, among his 16 technical books. His main Web site is at www.intuitive.com, and he also offers up tech support at AskDaveTaylor.com. You also can follow Dave on Twitter through twitter.com/DaveTaylor.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




4 hours 42 min ago
5 hours 15 sec ago
6 hours 53 min ago
8 hours 46 min ago
15 hours 40 min ago
15 hours 56 min ago
17 hours 48 min ago
23 hours 40 min ago
1 day 4 hours ago
1 day 4 hours ago