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
find /app/data/zips -depth \! -name "*.zip" -exec rm -rf -i -v '{}' +.sh script.shinstead of usingbash#!/bin/bash. What it does is find all files or directories in /app/data/zips that do NOT (the !) have the name *.zip and perform on them the action ofrm ....cdin a script, you need some sort of error checking on it -- if thecdfails for some reason, the rest of the script will execute in the wrong place, with potentially dangerous results. Suppose thatrmcommand ran in the wrong place!cdin scripts at all; instead, use explicit paths, likerm -rf -i -v /app/data/zips/!(*.zip),> /app/cronscripts/import/import_output.log, etc. When I need tocd, I like to use something likecd /somedir || { echo "Error changing directory" >&2; exit 1; }(see BashPitfalls #19). BTW, shellcheck.net is good at pointing out common mistakes like this.