我正在编写一个脚本,将多个文件组合成一个文件。我不知道输入/输出文件的名称和有多少个输入文件,我决定使用-i标志读取输入文件,使用-o标志指定输出文件。
请注意,这只是读取输入/输出文件的第一步。我正在处理多种格式的输入文件: txt,xlsx,rtf,pdf。因此,单个cat f1 f2 f3 > outfile在我的情况下不起作用。
#!/bin/bash
# This script merge txt,xlsx,rtf,pdf files in pdf_input folder into a single pdf file and save the output
# file to pdf_output folder
usage () {
echo "Script usage:"
echo " $0 -i <input file1>,<input file2>,<input file3>,... -o <combined output file>"
echo " If you have multiple input files, the file names need to be seperated by ,"
exit
}
while getopts ":i:o:" opt; do
case $opt in
i)
echo "Input file string = $OPTARG "
set -f
IFS=',' # split on space characters
array=($OPTARG) # use the split+glob operator
;;
o)
echo "Output file = $OPTARG"
;;
h)
usage
exit 0
;;
:)
echo "Error: -${OPTARG} requires an argument."
usage
exit 1
;;
*)
usage
exit 1
;;
esac
done
echo "Number of input files: ${#array[@]}"
echo -n "Input files are:"
for i in "${array[@]}"; do
echo -n " ${i} "
done:)可以很好地检查空参数。但是,如果我同时使用-o和-i标志,我会得到意想不到的结果。有没有办法检查两个标志上的空参数?
#./pdf_merge.sh -i a,b,c,d -o out
Input file string = a,b,c,d
Output file = out
Number of input files: 4
Input files are: a b c d
#./pdf_merge.sh -o
Error: -o requires an argument.
Script usage:
./pdf_merge.sh -i <input file1>,<input file2>,<input file3>,... -o <combined output file>
If you have multiple input files, the file names need to be seperated by ,
#./pdf_merge.sh -i
Error: -i requires an argument.
Script usage:
./pdf_merge.sh -i <input file1>,<input file2>,<input file3>,... -o <combined output file>
If you have multiple input files, the file names need to be seperated by ,
#./pdf_merge.sh -i -o
Input file string = -o
Number of input files: 1
Input files are: -o,
#./pdf_merge.sh -o -i
Output file = -i
Number of input files: 0发布于 2021-06-03 04:20:01
我在参数上添加了一个检查机制。这不是最干净的解决方案,但这是可行的。
while getopts ":i:o:" opt; do
case $opt in
i)
echo "Input file string = $OPTARG "
if [ "$OPTARG" == "-o" ]; then
echo "Input error! You need to have at least one input file"
usage
exit 1
fi
set -f
IFS=',' # split on space characters
array=($OPTARG) # use the split+glob operator
;;
o)
echo "Output file = $OPTARG"
if [ "$OPTARG" == "-i" ]; then
echo "Input error! You need to specify an output file"
usage
exit 1
fi
;;
h)
usage
exit 0
;;
:)
echo "Error: -${OPTARG} requires an argument."
usage
exit 1
;;
*)
usage
exit 1
;;
esac
done感谢大家的意见。
https://stackoverflow.com/questions/67730393
复制相似问题