Splitting a string to tokens according to shell pa

2019-08-05 07:40发布

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?

标签: bash shell sh
1条回答
家丑人穷心不美
2楼-- · 2019-08-05 08:28

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.

查看更多
登录 后发表回答