Scripting With The Shebang Line In Scripts
The shebang line is used to indicate what program the file should be fed into.
#!/usr/bin/env python3
print('hi')
But what does it look like to make a script that is used for the shebang line?
#!/my/script/here
This is the file that is loaded into my script.
Understanding what it does
We can start with a simple experiment to see what is passed in.
#!/usr/bin/env python3
# This script will be used FOR the shebang line in /usr/local/bin/sb_example
import sys
print(sys.argv)
We will make this an executable.
$ chmod +x /usr/local/bin/sb_example
For now let's just make any random script
#!/usr/local/bin/sb_example
hi
Run it and we get:
$ chmod +x my_script
$ ./my_script
['/usr/local/bin/sb_example', './my_script']
We see we get the filename as the argument.
What if we add command line arguments?
$ ./my_script run these arguments
['/usr/local/bin/sb_example', './my_script', 'run', 'these', 'arguments']
All we have to do now is make our script do something. Remember the file still
contains the shebang line and potentially empty lines after it so they should be
skipped.
Making a trivial script
Let's change our sb_example
to be an adding script. It will get all numbers in
a line and add them up. So a line that is 1 2
will output 1 + 2 = 3
. Many
numbers can be in a line.
#!/usr/bin/env python3
# /usr/local/bin/sb_example
import sys
for line in open(sys.argv[1]):
line = line.strip() # remove ending newlines
if line == '' or line[0] == '#':
continue # skip empty lines or lines starting with #, including shebang
numbers = line.split()
answer = sum(map(int, numbers))
print(f'{" + ".join(numbers)} = {answer}')
Now let's change the script that will use the script above in the shebang line.
#!/usr/local/bin/sb_example
1 2
3 4 5
6 7 8 9
$ ./my_script
1 + 2 = 3
3 + 4 + 5 = 12
6 + 7 + 8 + 9 = 30