Here is the video version, if you prefer it:
Today, let’s talk about special variables. Special variables are contained within every shell script and can be useful, depending on what you are doing. It pays to know them.
The first type of special variables we will cover are individual arguments to the shell script. (Ward, 2014) Let’s open up our tutorialScript.sh
and write (after the shebang):
echo $1
So our entire script looks like:
#!/bin/bash
echo $1
Make sure to save the script. Now, let us run our script by typing:
mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh
bash: ./tutorialScript.sh: Permission denied
Ooops! Let’s fix this by giving our user execute permissions. How to do so? Well, chmod of course:
mislav@mislavovo-racunalo:~/Linux_folder$ chmod 755 tutorialScript.sh
Now let’s run our script and pass it an argument as so:
mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh argument1
argument1
We see we get argument1
. Try putting echo $2
instead of echo $1
and then pass two arguments to your script. If the second argument is argument2
, you will get argument2
printed out. Try it out! No, really, try it out – it will take less than 1 minute of your time and it will solidify the concept, so it is a worthwhile investment based on time investment / gain ratio.
Here is a list of special variables you should try echoing out as well:
$#
– number of arguments$@
– all arguments$0
– script name$$
– process ID (of the shell running the script)$?
– exit code (will be covered later)
You can also shift arguments with the shift command, but I leave you to Google that if you ever need it.
Hope you learned something useful!
References
Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 253-255
Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.