首页 > 解决方案 > 如何在 shell 脚本中获取参数编号 i,其中 i 是一个变量

问题描述

我正在尝试制作一个以 shebang 开头的脚本#!/bin/sh,除其他外,它循环遍历脚本的arguments,以检查是否存在给定的参数。

到目前为止,这是我想出的:

#!/bin/sh

mother_flag="n"
virgin_flag="n"
reset_flag="n"

i=0
while [ $i -le $# ]
do
    echo "${i}" # <<< This line isn't doing what I want it to do!
    if [ ${i} = "--mother" ]; then
        mother_flag="y"
    elif [ ${i} = "--virgin" ]; then
        virgin_flag="y"
    elif [ ${i} = "--reset" ]; then
        reset_flag="y"
    fi
    i=$((i+1))
done

echo "mother_flag = $mother_flag"
echo "virgin_flag = $virgin_flag"
echo "reset_flag = $reset_flag"

这运行,但它没有做我想要它做的事情。如果我运行sh my_script --mother${i}给出 0 然后 1。我应该放什么来做${?}(或它的替代品)给my_script然后--mother?或者这在 shell 脚本中是不可能的?

还是有更好的方法来检查shell 脚本中的参数?

标签: sh

解决方案


推荐阅读