我有一系列命令,我在终端运行,我想知道如何将这些命令存储在一个文件和什么文件类型,以便打开该文件,在终端,命令运行?
但是命令需要两个输入源,我会在运行命令时手动输入.
有没有办法打开文件,它可以问我这两个输入,然后将它们插入命令,然后运行命令?
如果需要帮助我,文件中的命令是:
$cd scripts/x
$python x.py -i input -o output
所以在打开文件时我需要首先将dir更改为scripts / x,然后询问输入值,然后输出值,然后运行第二个命令.
我怎样才能做到这一点?
最佳答案 首先,在您喜欢的编辑器中创建此文件(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.