在shell脚本中如何传递多个参数
时间:2020-01-09 10:37:25 来源:igfitidea点击:
现在假设我们希望编写一个Shell脚本,该脚本需要多个输入参数来执行任务。
因此,处理这种情况变得不那么棘手。
因此,要在shell脚本中传递多个参数,我们将在示例中使用while循环。
在Shell脚本中传递多个参数的步骤
这是我们的第一个脚本,只有" show_usage"功能,其中包含该脚本将支持的输入参数列表。
在此示例中,我们将使用" if"条件来收集输入参数并相应地执行操作。
#!/bin/bash
##
# @Description: Steps to pass multiple parameters in shell script
# Take single argument
##
function show_usage (){
printf "Usage: # /tmp/collect_input.sh -hh
Incorrect input provided
Usage: /tmp/collect_input.sh [options [parameters]]
Options:
-n|--number, Print number
-s|--single [rpm_name], Print rpm version
-m|--mdstat, Print /proc/mdstst (Update)
-c|--collect, Collect rpm list to log file
-t|--timeout, Collect timeout
-p|--path, Provide the path
-h|--help, Print help
[options [parameters]]\n"
printf "\n"
printf "Options:\n"
printf " -n|--number, Print number\n"
printf " -s|--single [rpm_name], Print rpm version\n"
printf " -m|--mdstat, Print /proc/mdstst (Update)\n"
printf " -c|--collect, Collect rpm list to log file\n"
printf " -t|--timeout, Collect timeout\n"
printf " -p|--path, Provide the path\n"
printf " -h|--help, Print help\n"
return 0
}
if [[ "" == "--help" ]] || [[ "" == "-h" ]];then
show_usage
else
echo "Incorrect input provided"
show_usage
fi
因此,现在对于此脚本,如果我们提供--help或者-h,则脚本将执行show_usage函数。
现在,即使我们提供任何其他参数作为输入,脚本也将假定提供了错误的输入,并将再次执行show_usage函数。
输出:
case in
--number|-n)
shift
echo "You entered number as: "
shift
;;
--collect|-c)
shift
echo "You entered collect as: "
;;
--timeout|-t)
shift
echo "You entered timeout as:"
;;
*)
show_usage
;;
esac
接下来,我们将修改脚本以使用case而不是if。
在这种情况下,最好使用" case"而不是" if"条件。
这里的" show_usage"功能保持不变。
# /tmp/collect_input.sh -n 12 You entered number as: 12
现在让我们尝试使用单个输入参数执行脚本
输出:
# /tmp/collect_input.sh -n 12 -t 34 You entered number as: 12
这样就可以了,现在让我们尝试使用两个输入参数执行脚本
while [ ! -z "" ]; do
case "" in
--number|-n)
shift
echo "You entered number as: "
;;
--collect|-c)
shift
echo "You entered collect as: "
;;
--timeout|-t)
shift
echo "You entered timeout as: "
;;
*)
show_usage
;;
esac
shift
done
如我们所见,即使我给了两个参数,脚本也只能读取第一个参数。
为了解决这个问题,我们需要使用一个while循环。
# /tmp/collect_input.sh -n 12 -t 34 You entered number as: 12 You entered timeout as: 34
其中:我添加了一个额外的" while"循环,该循环将为提供给shell脚本的所有输入参数重新运行case语句。
让我们尝试在shell脚本中传递多个参数
# /tmp/collect_input.sh -n 12 -t 34 -c value You entered number as: 12 You entered timeout as: 34 You entered collect as: value
对于三个论点
##代码##因此,现在我们能够在shell脚本中传递多个参数。

