如何检测使用通配符(星号 *)作为 shell 脚本的参数? [英] How to detect using of wildcard (asterisk *) as parameter for shell script?

查看:28
本文介绍了如何检测使用通配符(星号 *)作为 shell 脚本的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的脚本中,如何区分何时使用星号通配符而不是强类型参数?

In my script, how can I distinguish when the asterisk wildcard character was used instead of strongly typed parameters?

这个

# myscript *

从这里

# myscript p1 p2 p3 ... (where parameters are unknown number)

推荐答案

shell 扩展了通配符.到脚本运行时,通配符已扩展,脚本无法判断参数是通配符还是显式列表.

The shell expands the wildcard. By the time a script is run, the wildcard has been expanded, and there is no way a script can tell whether the arguments were a wildcard or an explicit list.

这意味着您的脚本将需要其他非脚本的帮助.具体来说,在命令行处理之前运行的东西.那个东西是别名.这是你的别名

Which means that your script will need help from something else which is not a script. Specifically, something which is run before command-line processing. That something is an alias. This is your alias

alias myscript='set -f; globstopper /usr/bin/myscript'

这样做是设置一个名为myscript"的别名,所以当有人输入myscript"时,这就是运行的内容.别名有两件事:首先,它使用 set -f 关闭通配符扩展,然后它运行一个名为 globstopper 的函数,将路径传递给你的脚本,以及其余的命令行参数.

What this does is set up an alias called 'myscript', so when someone types 'myscript', this is what gets run. The alias does two things: firstly, it turns off wildcard expansion with set -f, then it runs a function called globstopper, passing in the path to your script, and the rest of the command-line arguments.

那么 globstopper 函数是什么?这:

So what's the globstopper function? This:

globstopper() {
  if [[ "$2" == "*" ]]
    then echo "You cannot use a wildcard"
    return
  fi
  set +f
  "$@";
}

这个函数做了三件事.首先,它检查脚本的参数是否是通配符(警告:它只检查第一个参数,并且只检查它是否是一个简单的星号;扩展它以涵盖更多情况,留给读者).其次,它重新打开通配符扩展.最后,它运行原始命令.

This function does three things. Firstly, it checks to see if the argument to the script is a wildcard (caveat: it only checks the first argument, and it only checks to see if it's a simple star; extending this to cover more cases is left as an exercise to the reader). Secondly, it switches wildcard expansion back on. Lastly, it runs the original command.

为此,您确实需要能够在用户的 shell 中设置别名和 shell 函数,并要求您的用户使用别名,而不是脚本.但如果你能做到这一点,它应该会奏效.

For this to work, you do need to be able to set up the alias and the shell function in the user's shell, and require your users to use the alias, not the script. But if you can do that, it ought to work.

我应该补充一点,我非常依赖于辉煌的 Simon Tatham 的文章魔术别名:Bourne Shell 中的分层漏洞'在这里.

I should add that i am leaning heavily on the resplendent Simon Tatham's essay 'Magic Aliases: A Layering Loophole in the Bourne Shell' here.

这篇关于如何检测使用通配符(星号 *)作为 shell 脚本的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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