将终端命令保存到文件中,当打开文件时在终端中运行该命令

4

我有一系列在终端中运行的命令,我想知道如何将这些命令存储在一个文件中,以及存储格式是什么,这样在打开该文件时,在终端中执行这些命令?

但是这些命令需要两个输入源,我需要手动输入这两个输入源。

当打开文件时,是否有办法询问我这两个输入源,然后将它们插入到命令中并运行命令?

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

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

在文件打开时,我需要它首先将目录更改为scripts / x,然后要求我提供输入值和输出值,最后运行第二个命令。你如何做到这一点?
2个回答

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脚本的知识,您可能需要阅读BashGuide初学者Bash指南,在这种情况下,您还应该检查BashPitfalls


非常感谢您的帮助和解释,对我很有帮助! - Irfan Mir
一个问题是,当我双击 X.sh 打开它时,终端会打开并关闭(很快就闪过了)。我猜这是因为我没有给它输入,它很快地打印出错误并关闭了。当 .sh 文件被双击并在终端中打开时,如何让终端打开并要求输入。 - Irfan Mir
如前所述,您可以使用read从标准输入(键盘)中读取文件名。因此,您可以使用read infile代替infile="$1"。例如,您可以对outfile执行相同的操作,并忽略顶部的参数计数检查。 - Adrian Frühwirth

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接