bash脚本在Linux中参数解析 [英] Bash Script with Parsing Argument in Linux
问题描述
我想要写一个bash脚本:
I want to write a bash script :
schedsim.sh [-h] [-c x] -i pathfile
其中:
•-h:打印当前用户名。
• -h: print the current username.
•-c X:得到一个选项参数x和打印出(X + 1)。如果没有找到说法,打印默认值为1。
• -c x : get an option-argument x and print out (x + 1). If no argument was found, print the default value is 1.
•-i pathfile:打印pathfile的大小。该pathfile是必需的参数。如果发现任何参数,打印出的错误消息。
• -i pathfile: print the size of pathfile. The pathfile is a required argument. If no argument was found, print out an error message.
这是我迄今所做的:
x=""
path=""
while getopts ":hc:i:" Option
do
case $Option in
h) echo -e "$USER\n"
;;
c) x=$optarg+1
;;
i) path=$(wc -c <"$optarg")
;;
esac
done
if [ -z "$x"]
then
echo -e "$x\n"
else
echo 1
fi
if [ -z "$path"]
then
echo $path
else
echo "Error Message"
exit 1
fi
如何完成选项参数,所需参数的部分和错误信息的一部分?
How to finish the option-argument,required-argument part and the error message part?
推荐答案
一个重写:
while getopts ":hc:i:" Option; do
case $Option in
h) echo "$USER"
;;
c) x=$(($OPTARG + 1))
;;
i) if [[ -f $OPTARG ]]; then
size=$(wc -c <"$OPTARG")
else
echo "error: no such file: $OPTARG"
exit 1
fi
;;
esac
done
if [[ -z $x ]]; then
echo "you used -c: the result is $x"
fi
if [[ -z $size ]]; then
echo "you used -i: the file size is $size"
fi
注:
-
OPTARG
必须是大写。 - 您需要
$((...))
对于bash算术 - 检查该文件在使用它之前存在
- 使用一个明智的文件名(
路径
不会重新present一个文件的大小) - 有必须的是一个空格
]
-
回声-e值\\ N
是太多的工作:你只是想回声值
除非你要处理的值转义序列:
OPTARG
must be in upper case.- you need
$((...))
for bash arithmetic - check that the file exists before using it
- use a sensible filename (
path
does not represent the size of a file) - there must be a space before
]
echo -e "value\n"
is too much work: you just wantecho "value"
unless you want to process escape sequences in the value:
$ var="foo\tbar\rbaz"
$ echo "$var"
foo\tbar\rbaz
$ echo -e "$var\n"
baz bar
$
更新:回复评论:简化和更完整的选项处理;扩展错误处理。
Update: responding to comments: simplified and more complete option handling; expanded error handling.
#!/bin/bash
declare -A given=([c]=false [i]=false)
x=0
path=""
while getopts ":hc:i:" Option; do
case $Option in
h) echo "$USER"
;;
c) x=$OPTARG
given[c]=true
;;
i) path=$OPTARG
given[i]=true
;;
:) echo "error: missing argument for option -$OPTARG"
exit 1
;;
*) echo "error: unknown option: -$OPTARG"
exit 1
;;
esac
done
# handle $x
if [[ ! $x =~ ^[+-]?[[:digit:]]+$ ]]; then
echo "error: your argument to -c is not an integer"
exit 1
fi
if ! ${given[c]}; then
printf "using the default value: "
fi
echo $(( 10#$x + 1 ))
# handle $path
if ! ${given[i]}; then
echo "error: missing mandatory option: -i path"
exit 1
fi
if ! [[ -f "$path" ]]; then
echo "error: no such file: $path"
exit 1
fi
echo "size of '$path' is $(stat -c %s "$path")"
这篇关于bash脚本在Linux中参数解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!