选择文件时bash脚本中意外标记'('附近的语法错误 [英] syntax error near unexpected token '(' in bash script when selecting files

查看:117
本文介绍了选择文件时bash脚本中意外标记'('附近的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此脚本bash ./cleanup.bash

#!/bin/bash
## going to dir moving stuff
rm -rf !(composer.json|.git)

给出错误:

cleanup.bash:第10行:意外令牌'('附近的语法错误 cleanup.bash:第10行:"rm -rf!(composer.json | .git)"

cleanup.bash: line 10: syntax error near unexpected token '('
cleanup.bash: line 10: 'rm -rf !(composer.json|.git)'

但是如果我直接在终端中运行,没问题rm -rf !(composer.json|.git)

But if I run in in the terminal directly no problem rm -rf !(composer.json|.git)

我尝试剥离所有其他行,但仍然收到错误消息.

I tried stripping out all other lines, still get the error.

如何在bash脚本中正确输入?

How do I enter this correctly in the bash script?

推荐答案

我猜您的问题是由于从脚本运行时未设置shell扩展glob选项.当您声明它可以在命令行中运行时,您可以通过某种方式设置extglob标志,该标志允许使用!() glob.

I guess your problem is due the shell extended glob option not set when run from the script. When you claim it works in the command line, you have someway set the extglob flag which allow to !() globs.

由于bash脚本每当以#!/bin/bash开头时都会启动新的子shell,因此在父shell中设置的扩展选项可能不会反映在新shell中.要使其生效,请在爆炸后在脚本中进行设置

Since the bash script whenever started with a #!/bin/bash starts a new sub-shell the extended options set in the parent shell may not be reflected in the new shell. To make it effect, set it in the script after the she-bang

#!/bin/bash

shopt -s extglob

## going to dir moving stuff
rm -rf !(composer.json|.git)

这篇关于选择文件时bash脚本中意外标记'('附近的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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