Home > Software engineering >  bash syntax error for adding '(' character in bash script
bash syntax error for adding '(' character in bash script

Time:09-23

I am running the following command on the Linux command line

cp !(non_*).txt some_folder/

It is working as expected (i.e., copy all *.txt files except the files starting with 'non_' in the current folder to some_folder.)

But when the same line is added to a script file and executing it with ./script.sh

it is throwing the following error.

./script.sh: line 1: syntax error near unexpected token `('

./script.sh: line 1: ` cp !(oam_cfg*).txt kk/'

What can be the correction here?

FYI: I am trying to copy all *.txt files except the files starting with 'non_' in the current folder to some_folder.

CodePudding user response:

As Jetchisel commented an hour ago, you need to turn on extended globbing.

An example:

$: touch foo.txt bar.txt  # create a file
$: echo  (foo*txt)        # use an extended glob, which fails on syntax
bash: syntax error near unexpected token `('
$: shopt -s extglob  # turn extended globbing *ON*
$: echo  (foo*txt)   # same command now succeeds
foo.txt
$: echo !(foo).txt   # negative works as well
bar.txt
  • Related