I have the following script :
#!/bin/bash
# initialisation of the script
mkdir -p test_dir
touch test_dir/test{1..15}
touch test_dir/test{a..e}
# enabling etended glob
shopt -s extglob
# we count the number of files which name is touchNUMBER
for f in test_dir/test+([0-9]); do ((count++)); done; echo $count
It works just fine and prints 15.
However, when I try to concatenate this script to a one-liner, it returns an error :
#!/bin/bash
mkdir -p test_dir
touch test_dir/test{1..15}
touch test_dir/test{a..e}
shopt -s extglob; for f in test_dir/test+([0-9]); do ((count++)); done; echo $count
Output :
./test.sh: line 7: syntax error near unexpected token `('
It seems bash doesn't evaluate the shopt -s extglob before determining the correctness of the syntax of this line.
EDIT:
Interestingly enough, replacing the incriminated line with :
shopt -s extglob; sleep 10;for f in test_dir/test+([0-9]); do ((count++)); done; echo $count
Displays the same error message instantly, thus confirming the error message is raised before the execution of the line.
Why is that ? Is there a way around ?