Abdul Moiz
Abdul Moiz

Reputation: 1327

Command is working on terminal but not giving syntax error in bash script

Below is my script placed in /usr/bin as I want to make it available globally

#!/bin/bash
cd /app/data/zips
rm -rf -i -v !(*.zip)
cd /app/cronscripts/import
> import_output.log
nohup ./import.sh > import_output.log & disown

Everything in the above script is working perfectly fine apart from the below-given line, however, this command is working perfectly fine when running it from the terminal directly. It's for deleting all files and folders except .zip files in the directory

rm -rf -i -v !(*.zip)

Whenever I try to run this script it gives me the following error.

/usr/bin/importdata.sh: line 3: syntax error near unexpected token `('
/usr/bin/importdata.sh: line 3: `rm -rf -i -v !(*.zip)'

My which bash output is:

/bin/bash

OS information:

Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:        18.04
Codename:       bionic

Upvotes: 0

Views: 493

Answers (1)

user13655578
user13655578

Reputation:

In bash, !(pattern) is an extended glob pattern. Turn on the shell option which enables that:

shopt -s extglob

shopt should appear on its own line at the start of the script, along with any other options which you may be relying on. See wooledge: https://mywiki.wooledge.org/glob#Options_which_change_globbing_behavior

extglob changes the way certain characters are parsed. It is necessary to have a newline (not just a semicolon) between shopt -s extglob and any subsequent commands to use it. You cannot enable extended globs inside a group command that uses them, because the entire block is parsed before the shopt is evaluated.

Upvotes: 5

Related Questions