带有通配符和括号的 ls 在控制台中有效,但在脚本中无效

RoF*_*oFr 5 command-line bash scripts

命令

ls /etc/pve/lxc/*([0-9]).conf
Run Code Online (Sandbox Code Playgroud)

在控制台中工作

  • 结果:文件找到!
/etc/pve/lxc/107.conf
Run Code Online (Sandbox Code Playgroud)

但不在脚本中

  • #!/bin/bash
  • 结果:错误
syntax error near unexpected token `('
ls /etc/pve/lxc/*([0-9]).conf
Run Code Online (Sandbox Code Playgroud)

然后我屏蔽了脚本中的括号

/etc/pve/lxc/107.conf
Run Code Online (Sandbox Code Playgroud)
  • 结果:未找到文件
ls: cannot access '/etc/pve/lxc/*([0-9]).conf': No such file or directory
Run Code Online (Sandbox Code Playgroud)

ste*_*ver 15

该表达式*([0-9]).conf是 KSH 样式的扩展 glob。默认情况下,交互式 bash shell 启用该功能,但要在 bash 脚本中使用它,必须使用显式启用

shopt -s extglob
Run Code Online (Sandbox Code Playgroud)

另请参阅在命令行上有效但在 bash 脚本中无效的通配符扩展


van*_*ium 7

您未提供的信息是脚本中使用的命令解释器。这由 shebang 表示,即第一行(例如#/bin/sh)。

在 Ubuntu 中,控制台默认运行 bash 作为交互式 shell。如果您的脚本使用其他命令解释器,例如/bin/sh,则特定于bash 的语法将不起作用。