Splitting a string to tokens according to shell parameter rules without eval

只谈情不闲聊 提交于 2019-12-11 09:29:18

问题


I have a string like

$ str="abc 'e f g' hij"

and i wish to get whole e f g part of it. In other words, i wish to tokenize the string according to shell parameter rules.

Currently, i am doing that as

$ str="abc 'e f g' hij"; (eval "set -- $str"; echo $2)

but this is totally unsafe if a single * gets outside of '-ticks.

Any better solutions?


回答1:


You can use set -f to disable filename expansion altogether.

$ str="* 'e f g' hij"
$ ( set -f; eval "set -- $str"; echo $2 )
e f g

This addresses just one problem you might anticipate with eval, but there may be other options available with set you can explore.



来源:https://stackoverflow.com/questions/14913678/splitting-a-string-to-tokens-according-to-shell-parameter-rules-without-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!