解析shell脚本参数 [英] Parsing shell script arguments

查看:132
本文介绍了解析shell脚本参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$myscript.sh -host blah -user blah -pass blah

我想参数传递到它。

I want to pass arguments into it.

我是用来干什么的 $ 1 $ 2 $ 3 ....但我要开始给它们命名

I'm used to doing $1, $2, $3....but I want to start naming them

推荐答案

有很多方法在SH解析参数。 getopt的还是不错的。下面是手工解析事物的简单脚本:

There are lots of ways to parse arguments in sh. Getopt is good. Here's a simple script that parses things by hand:

#!/bin/sh

while echo $1 | grep -q ^-; do
    eval $( echo $1 | sed 's/^-//' )=$2
    shift
    shift
done

echo host = $host
echo user = $user
echo pass = $pass
echo args = $@

一个样本来看是这样的:

A sample run looks like:

$ ./a.sh -host foo -user me -pass secret some args
host = foo
user = me
pass = secret
args = some args

请注意,这不是甚至远程健壮和大规模开放安全
由于脚本的eval孔是由用户构建的字符串。它仅仅是
意在作为一种可能的方式做的事情,例如,一个更简单的方法是要求用户通过在环境中的数据。在Bourne shell(即任何不在CSH族):

Note that this is not even remotely robust and massively open to security holes since the script eval's a string constructed by the user. It is merely meant to serve as an example for one possible way to do things. A simpler method is to require the user to pass the data in the environment. In a bourne shell (ie, anything that is not in the csh family):

$ host=blah user=blah pass=blah myscript.sh

工作得很好,并且变量 $主机 $用户 $通过将在脚本中。

#!/bin/sh
echo host = ${host:?host empty or unset}
echo user = ${user?user not set}
...

这篇关于解析shell脚本参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆