将terminal命令保存到打开时在终端中运行命令的文件

时间:2013-04-21 07:25:51

标签: shell command-line terminal command

我在终端中运行了一系列命令,我想知道如何将这些命令存储在一个文件中以及文件类型中,以便在打开该文件时,在终端中运行命令?

但是这些命令需要两个输入源,我会在运行命令时手动输入。

文件是否有打开方式,它可以询问我这两个输入,然后将它们插入命令然后运行命令?

如果需要帮助我,文件中的命令是:

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

所以在文件打开时我需要先将dir更改为scripts / x,然后询问输入值,然后输出值,然后运行第二个命令。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

首先,在您喜欢的编辑器中创建此文件(x.sh):

#!/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}"

然后,您需要将其设为可执行文件(请输入man chmod以获取更多信息):

$ chmod +x ./x.sh

现在,您可以使用./x.sh从同一文件夹运行此脚本,例如

$ ./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

请注意,如果输出文件名以某种方式基于输入文件名,则可以避免在命令行中指定它,例如:

$ infile="myfile.oldextension"
$ outfile="${infile%.*}_converted.newextension"
$ printf "infile:  %s\noutfile: %s\n" "${infile}" "${outfile}"
infile:  myfile.oldextension
outfile: myfile_converted.newextension

如您所见,这里有改进的余地。例如,我们不检查scripts/x目录是否确实存在。如果您真的希望脚本询问您的文件名,并且根本不想在命令行中指定它们,请参阅man read

如果您想了解有关shell脚本的更多信息,可能需要阅读BashGuideBash Guide for Beginners,在这种情况下,您还应该查看BashPitfalls

答案 1 :(得分:0)

usage ()
{
  echo usage: $0 INPUT OUTPUT
  exit
}

[[ $2 ]] || usage
cd scripts/x
python x.py -i "$1" -o "$2"