You need to add the interpreter to the head of your script and also use the sys.env
to access the input parameters:
#!/usr/bin/python
import sys, os;
# check so we have enough arguments
if len(sys.argv) < 2:
printf "You need to supply at least two arguments."
exit(-1)
# check so the file exists
if os.path.exists(sys.argv[1]):
# try to open the filename supplied in the second argument
# the sys.argv[0] always points to the name of the script
with open(sys.argv[1], 'r') as f:
for i in f:
print i
else:
print 'The file %s does not exists' %(sys.argv[1])
Notice that you might need to change the /usr/bin/python
to the path where your python binary is installed. You can find out where it is by issuing the following command:
whereis python
Now you should be able to run your command like this:
./command file.txt
Notice, that here I assume that you are standing in the same folder as the python script. You could also move the script into a folder which is in your $PATH
environment variable so you could access it from everywhere. For instance you could move it to /usr/local/bin
:
mv command /usr/local/bin/.
You should then be able to run it from any folder using:
command file.txt
The last thing you need to do is to make sure the script is executable:
chmod +x command