gpt4 book ai didi

linux - Linux 中带有解析参数的 Bash 脚本

转载 作者:太空狗 更新时间:2023-10-29 12:13:41 29 4
gpt4 key购买 nike

我想写一个 bash 脚本:

schedsim.sh [-h] [-c x] -i pathfile

地点:

• -h:打印当前用户名。

• -c x:获取选项参数 x 并打印出 (x + 1)。如果未找到参数,则打印默认值为 1。

• -i 路径文件:打印路径文件的大小。路径文件是必需的参数。如果没有找到参数,则打印出一条错误消息。

这是我到目前为止所做的:

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

如何完成选项参数、必需参数部分和错误信息部分?

最佳答案

重写:

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 运算
  • 使用前检查文件是否存在
  • 使用合理的文件名(路径不代表文件的大小)
  • 必须]之前有一个空格
  • echo -e "value\n" 工作量太大:你只需要 echo "value" 除非你想处理值中的转义序列:

    $ var="foo\tbar\rbaz"
    $ echo "$var"
    foo\tbar\rbaz
    $ echo -e "$var\n"
    baz bar

    $

更新:回应评论:简化和更完整的选项处理;扩展错误处理。

#!/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")"

关于linux - Linux 中带有解析参数的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32826395/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com