Save the terminal command to a file that launches the command in the terminal upon opening

I have a number of commands that I run in the terminal, and I wonder how I can store these commands in a file and what type of file to execute when opening this file in the terminal?

But commands require two input sources that I would manually enter when I run the command.

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

commands inside the file, if necessary, to help me:

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

So, when I open the file, I need to change the directory to the / x scripts first, then ask me the input value, then the output value, and then run the second command.

How can i do this?

+4
source share
2 answers

First create this file ( x.sh ) in your favorite editor:

 #!/bin/bash # the variable $# holds the number of arguments received by the script, # eg 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 more information):

 $ chmod +x ./x.sh 

Now you can run this script from the same folder using ./x.sh , for example.

 $ ./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 name of the input file, you can omit 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. For example, we do not check if the scripts/x directory exists. And if you really want the script to ask you for the file names and do not want to specify them on the command line at all, see man read .

If you want to know more about shell scripts, you can read the BashGuide and Bash Guide for Beginners , in which case you should also check out BashPitfalls .

+2
source
 usage () { echo usage: $0 INPUT OUTPUT exit } [[ $2 ]] || usage cd scripts/x python x.py -i "$1" -o "$2" 
0
source

All Articles