用正确的引用自动重写bash脚本的工具? [英] Tool to automatically rewrite a bash script with proper quoting?

查看:58
本文介绍了用正确的引用自动重写bash脚本的工具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使大型代码库的所有bash脚本均 shellcheck 兼容,但任务是不堪重负,因为历史上有太多开发人员都忽略了所有shell脚本中的规则编号:始终使用引号.

如果有一个至少可以解决引用问题的工具,将对您有所帮助.然后,我将可以手动修复其余部分.我的正则表达式没有删减它,因为只有字符串中已经存在的 not 变量必须被引用.

样本输入:

  echo立即删除$ a $ {b} $(c $(c))`d $ d` $ {10} $ @"rm -rf $ a $ {b} $(c $(c))`d $ d` $ {10} $ @ 

样本输出:

  echo立即删除$ a $ b $(c" $(c))`d" $ d`$ {10} $ @"rm -rf"$ a""$ b""$(c" $(c))""$(d" $ d)""$ {10}""$ @" 

它不必修复以上所有问题,它甚至也不必完美无瑕(尽管那确实很不错),但它必须经常是对的,而不是有用的.


这是我没有用过的朴素正则表达式:

  s:([[^])\ $ \ {([_ A-Za-z0-9] +)\}([[^"] | $):\ 1"\ $ \ 2" \3:克 

它将$ {identifier}转换为"$ identifier",除非在引号之前或之后立即加引号,但无法检测到我们是否在字符串中更深.

解决方案

WPomier击败了我,但我也做了我自己的(因为我想这样做):
https://github.com/anordal/shellharden

它充当语法高亮显示,直到为它提供-transform 选项.

I'm contemplating to make all bash scripts of a large codebase shellcheck compliant, but the task is overwhelming, because too many developers have historically ignored rule number one of all shell scripting: always use quotes.

It would be helpful if there was a tool that could fix at least the quoting. I would then be able to fix the rest by hand. My regex didn't cut it, because only variables not already in a string must be quoted.

Sample input:

echo "Removing $a ${b} $(c $(c)) `d $d` ${10} $@ now"
rm -rf $a ${b} $(c $(c)) `d $d` ${10} $@

Sample output:

echo "Removing $a $b $(c "$(c)") `d "$d"` ${10} $@ now"
rm -rf "$a" "$b" "$(c "$(c)")" "$(d "$d")" "${10}" "$@"

It doesn't have to fix all the above, and it doesn't even have to be flawless (though that would be really nice), but it has to be right more often than not to be useful.


Here is my naïve regex that didn't cut it:

s:([^"])\$\{([_A-Za-z0-9]+)\}([^"]|$):\1"\$\2"\3:g

It transforms ${identifier} to "$identifier", except when immediately preceded or followed by a quote, but fails to detect if we are deeper within the string.

解决方案

WPomier beat me to it, but I did my own as well (because I wanted to):
https://github.com/anordal/shellharden

It acts as a syntax highlighter, until you give it the --transform option.

这篇关于用正确的引用自动重写bash脚本的工具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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