First, create this file (x.sh
) in your favourite editor:
#!/bin/bash
# the variable $# holds the number of arguments received by the script,
# e.g. when run as "./x.sh one two three" -> $# == 3
# if no input and output file given, throw an error and exit
if (( $# != 2 )); then
echo "$0: invalid argument count"
exit 1
fi
# $1, $2, ... hold the actual values of your arguments.
# assigning them to new variables is not needed, but helps
# with further readability
infile="$1"
outfile="$2"
cd scripts/x
# if the input file you specified is not a file/does not exist
# throw an error and exit
if [ ! -f "${infile}" ]; then
echo "$0: input file '${infile}' does not exist"
exit 1
fi
python x.py -i "${infile}" -o "${outfile}"
Then, you need to make it executable (type man chmod
for further info):
$ chmod +x ./x.sh
Now you can run this script from the same folder with ./x.sh
, e.g.
$ ./x.sh one
x.sh: invalid argument count
$ ./x.sh one two
x.sh: input file 'one' does not exist
$ ./x.sh x.sh foo
# this is not really printed, just given here to demonstrate
# that it would actually run the command now
cd scripts/x
python x.py -i x.sh -o foo
Note that if your output file name is somehow based on the input file name, you could avoid having to specify it on the command line, for example:
$ infile="myfile.oldextension"
$ outfile="${infile%.*}_converted.newextension"
$ printf "infile: %s\noutfile: %s\n" "${infile}" "${outfile}"
infile: myfile.oldextension
outfile: myfile_converted.newextension
As you can see, there is room for improvement here. For example, we don't check if the scripts/x
directory actually exists. And if you really want the script to ask you for the filenames and don't want to specify them on the command line at all, see man read
.
If you want to learn more about shell scripting, you might want to read the BashGuide and the Bash Guide for Beginners in which case you should also check the BashPitfalls.