2013-04-21 237 views
4

我有一系列我在终端中运行的命令,我想知道如何将这些命令存储在文件中以及如何在打开文件时文件,在终端,命令运行?保存终端命令到打开时在终端运行命令的文件

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

有没有办法打开文件,它可以问我这两个输入,然后将它们插入命令,然后运行命令?

文件中的命令,如果需要的话帮我,有:

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

于是就打开文件我需要它的目录先更改为脚本/ X,然后问我要输入的值,然后输出值,然后运行第二个命令。

我该怎么做?

回答

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

+0

非常感谢您的解答。这非常有帮助! – 2013-04-21 08:19:50

+0

有一个问题,当我双击X.sh打开它时,终端打开和关闭(这是一个快速闪烁)。我认为这是因为我没有给它输入信息,而且它很快打印错误并关闭。当双击.sh文件并在终端中打开时,如何让终端打开询问输入。 – 2013-04-21 08:46:24

+0

如上所述,您可以使用'read'来...从标准输入(您的键盘)读取文件名。因此,例如,可以使用'read infile'来代替'infile =“$ 1”'。你会为'outfile'做同样的事情,并忽略顶部参数数量的检查。 – 2013-04-23 16:51:06

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

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