How to Use $0 and $1 in a Shell Script
You may come across, as well as use, a couple of positional parameters when dealing with shell scripts. This is because positional parameters are built-in variables, and they are vital for using command-line arguments in a shell script.
Here you will find out:
- what positional parameters are
- what the $0 and $1 in a shell script mean
- whether it is important to know positional parameters or not
- when DiskInternals can help you
Are you ready? Let's read!
Positional parameters
For example, you can have $N, where N is the positional variable, and it must be a single digit.
However, you must enclose a positional parameter with brackets when it is expanded and has more than one digit: (${N}).
To set and/or unset positional parameters, you need to use the shell’s built-in set and shift commands.
Note: positional parameters can be 1, 2, 3, 4, 5, etc. This implies you’ll write them this way: $1, $2, $3, $4, $5, etc. Furthermore, 0 is a positional parameter, but it is set as the script’s name.
What do the $0 and $1 in a shell script mean?
Having learned that positional parameters are donated by $0, $1, ….$N, you might ask: what do $0 and $1 entail? $0 will expand to output the name of your shell script or the shell itself. On the other hand, $1, $2,… $N are the arguments for the $0 command.
Example:
Practical example:
Using $0 and $1 in a shell script
These practical examples show how to use $0 and $1 in shell scripts:
When you run a script named test.sh:
The output will be:
Note: if you run the above script using bash, $0 will return test.sh instead of ./test.sh.
Thus, in simple terms:
- $0 outputs the "program_or_script_name"
- $1 outputs "the_first_word"
- $2 outputs "the_second_word"
Why is it important to know positional parameters?
The main reason why you should know and understand these positional parameters is because they will help you to write and read shell scripts properly. Interestingly, these parameters can be used in any bash/shell script. They can make a script appear very complex to someone who doesn’t understand positional parameters, but for those who understand positional parameters, they make things easier.
It’s so easy to open Linux files from Windows
You may not believe it, but it’s true: you can easily access and open your Linux files on a Windows PC. DiskInternals Linux Reader is a handy freeware program specially designed for dual-boot and virtual machines users. It is an intuitive software tool that works with most file systems: Ext2/3/4, ReiserFS, Reiser4, HFS, HFS+, FAT, exFAT, NTFS, ReFS, UFS2, RomFS(reader), ZFS (preview only*), XFS (preview only*), Hikvision NAS and DVR (preview only*).
Also, DiskInternals Linux Reader displays all your Linux partitions in a straightforward interface and lets you access them at ease to find your Linux files.