4

I have a series of commands that I run in terminal and I am wondering how I can store those commands in a file and of what file type so that on open of that file, in terminal, the commands run?

But the commands require two sources of input that I would manually type in when running the command.

Is there a way on file open, it can ask me for these two inputs and then insert them into the command and then run the command?

the commands inside the file, if needed to help me, are:

$ cd scripts/x
$ python x.py -i input -o output

So on file open I need it to first change the dir to scripts/x, then ask me for the value of input, then the value of output, and then run the second command.

How can I do this?

4

2 回答 2

2

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.

于 2013-04-21T07:59:49.243 回答
0
usage ()
{
  echo usage: $0 INPUT OUTPUT
  exit
}

[[ $2 ]] || usage
cd scripts/x
python x.py -i "$1" -o "$2"
于 2013-04-21T07:59:18.877 回答