尝试通过 bash/shell 脚本运行 python 脚本,找出接受参数中的多个参数并循环遍历 $5 中的所有参数以在 $5 中的每个地址上运行相同命令的最佳方式是什么。另外,有没有办法在运行shell脚本时不传入空参数?以下是我到目前为止所做的工作,但对此处使用的特殊参数概念感到困惑https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
#!/bin/bash
# Arguments
echo "Service: $1"
echo "Action: $2"
echo "file: $3"
echo "DockerV: $4"
echo "Address: $5"
python /scripts/service.py -s "$1" -t "$2" "$5"
Running it this way works, but only if empty quotes are passed in---
/users/shellScripts/serviceTest.sh "ALL" "Stop" " " " " "11.45.26.13"
Running it this way does not works, as $5 has more than 1 argument---
/users/shellScripts/serviceTest.sh "ALL" "Stop" " " " " "11.45.26.13 11.45.26.14 11.45.26.15"
我尝试了上面写的脚本,但对 bash/shell 的特殊参数的概念感到困惑。期望在没有空参数的情况下执行 shell 脚本(也许将它们设置为可选),也能够将多个参数传递到一个参数中,并循环遍历 $5 中的所有参数,以在 $5 中的每个地址上运行相同的命令。
在参数中接受多个参数的最佳方式是什么
最好的方法是使用单独的参数,而不是将多个逻辑上不同的值打包到一个中。 如果您必须将多个逻辑上不同的值打包到一个参数中,那么有多种方法可以将它们分开。在您的情况下,您似乎是通过空格分隔值,并且它们不能包含内部空格。在这种情况下,您可以使用 shell 分词将它们分开。
循环遍历$5中的所有参数
shell 有一个
for
循环,在这种情况下,您可以像这样使用它:
# intentionally omitting quotes around $5 on the next line:
for addr in $5; do
python /scripts/service.py -s "$1" -t "$2" "$addr"
done
但是如果您将所有地址作为单独的参数传递,那么您可以这样做:
service=$1
action=$2
file=$3
docker_v=$4
shift 4
for addr in "$@"; do
python /scripts/service.py -s "$service" -t "$action" "$addr"
done
当脚本使用位置为其参数指定重要性,并且可选参数后面有必需参数时则不然。
对于具有大量参数或任何可选参数的脚本,使用标志(例如
-s
命令中的
-t
和 python
)来识别其参数的重要性会更惯用。特别是可选参数。但是参数处理会让你的脚本变得更加复杂,所以如果这不需要达到生产质量,那么也许你应该考虑只接受空参数。说到空论,""
和
''
都是空的。 " "
not空——它代表空格字符。
这样的选项解析器。
#!/bin/bash
args=()
while getopts ':s:t:' opt ; do
case $opt in
s) args+=( -s "$OPTARG" ) ;;
t) args+=( -t "$OPTARG" ) ;;
?) echo "Invalid option $OPTARG" ;;
:) echo "Option $OPTARG needs an argument" ;;
esac
done
shift $(( OPTIND - 1 ))
for ip in "$@" ; do
python /scripts/service.py "${args[@]}" "$ip"
done
调用示例:
/users/shellScripts/serviceTest.sh -s "ALL" -t "Stop" 11.45.26.13 11.45.26.14 11.45.26.15
重要注意事项: