How to use the /usr/bin/env command in a shell script
Here you will find out:
- why you need to use the /usr/bin/env command
- how to use ENV in a script
- how to define the path for the ENV command
- when DiskInternals can help you
Are you ready? Let's read!
Why you need to use the /usr/bin/env command
If you have noticed, all shell scripts usually start with this line:
While Perl scripts start with:
This first line is simply referred to as a shebang. Everything written on this line is very important for running your bash or Perl script. Typically, a UNIX system will read the interpreter defined on the first line of a script, be it bash or Perl. But, bash or Perl is not always on the same path as /bin/bash or /usr/bin/Perl. Thus, if you wish for your script to run across all UNIX-like OSes, you need to use the /usr/bin/env command as the shebang for your script.
Portability with #!/usr/bin/env
Using the ENV command, you can make your script run across UNIX-like systems without limitations. The command introduces a direction to call sh/bash/Perl.
Examples:
From the examples above, the ENV utility will invoke the first sh or bash executable found in the user's $PATH.
Another portability problem faced by most users is the interpretation of arguments. Normally, Linux and Cygwin systems do not split up arguments. For example:
From the command above, “python -c” is expected to run as one argument on /usr/bin/env.
How to use ENV in a script
The following is how you can use the ENV command in a script.
ENV works for different purposes, which include:
- Printing all environment variables
- Executing other commands in a custom environment
- Modifying the value of variables
- Adding or removing variables
How to define the path for the ENV command
Using TYPE or COMMAND, you can set a path ENV command:
Input:
Output:
Different *nix systems will print the following as the path for ENV command:
Examples of using ENV
Perl example:
Python 2.x example:
How to get files from Linux onto Windows
Because Windows does not support EXT partitions or other Linux-compatible partitions, it is difficult to open Linux files on Windows. However, using DiskInternals Linux Reader, you can access and open all Linux partitions while running Windows. This is especially good for dual-boot PC users and virtual machine users. DiskInternals Linux Reader is fast, intuitive, and free to download. With Linux Reader, you can view all kinds of files from Linux partitions, including media files and documents.