2013-04-21 235 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"