首先,在你喜歡的編輯器創建這個文件(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腳本的信息,您可能需要閱讀BashGuide和Bash Guide for Beginners,在這種情況下,您還應該檢查BashPitfalls。
非常感謝您的解答。這非常有幫助! – 2013-04-21 08:19:50
有一個問題,當我雙擊X.sh打開它時,終端打開和關閉(這是一個快速閃爍)。我認爲這是因爲我沒有給它輸入信息,而且它很快打印錯誤並關閉。當雙擊.sh文件並在終端中打開時,如何讓終端打開詢問輸入。 – 2013-04-21 08:46:24
如上所述,您可以使用'read'來...從標準輸入(您的鍵盤)讀取文件名。因此,例如,可以使用'read infile'來代替'infile =「$ 1」'。你會爲'outfile'做同樣的事情,並忽略頂部參數數量的檢查。 – 2013-04-23 16:51:06