选择文件时,Bash 脚本中出现“意外标记附近的语法错误"(“"错误) [英] Error "syntax error near unexpected token '('" in Bash script when selecting files

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

问题描述

运行这个脚本,bash ./cleanup.bash,

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

给出错误:

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

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

但是如果我直接在终端里跑进去,是没有问题的:

But if I run in in the terminal directly, there aren't any problems:

rm -rf !(composer.json|.git)

我尝试删除所有其他行,但仍然出现错误.

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

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

How do I enter this correctly in the Bash script?

我使用的是 Ubuntu,这一切都是在本地完成的,而不是远程完成.

I'm on Ubuntu, and this was all done locally, not on a remote.

推荐答案

我猜您的问题是由于从脚本运行时未设置 shell 扩展 glob 选项.当你声称它在命令行中工作时,你以某种方式设置了 extglob 标志,它允许 !() globs.

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

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

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 take effect, set it in the script after the shebang:

#!/bin/bash

shopt -s extglob

## Going to directory-moving stuff
rm -rf !(composer.json|.git)

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

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