Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script and regex issue

Let's imagine that on my server, i have the following files :

foo@bar:/var/log/foo$ ls
fooFile1 fooFile2 logFile logFile.1 logFile.2

I wanted to create an archive containing every file but logFile.*. So I came up with the command :

foo@bar:~$ tar -czf foo.tar.gz /var/log/foo/!(logFile.*)

And it works fine ! However, when trying to create a script which does the same job :

#!/bin/bash

tar -czf foo.tar.gz /var/log/foo/!(logFile.*)

I came across the following error :

./test.sh: line 3: syntax error near unexpected token '('
./test.sh: line 3: 'tar -czf foo.tar.gz /var/log/foo/!(logFile.*)'

The problem is not tar related (I met the same issue using ls instead of tar)

I don't understand where this error is coming from. Could anyone tell me where i am wrong ?

Met on Ubuntu 12.04

like image 410
Thomas Benard Avatar asked Jan 07 '15 15:01

Thomas Benard


People also ask

Can you use regex in bash script?

Regex is a very powerful tool that is available at our disposal & the best thing about using regex is that they can be used in almost every computer language. So if you are Bash Scripting or creating a Python program, we can use regex or we can also write a single line search query.

Does Linux support regex?

Regular expression is also called regex or regexp. It is a very powerful tool in Linux. Regular expression is a pattern for a matching string that follows some pattern. Regex can be used in a variety of programs like grep, sed, vi, bash, rename and many more.

What does =~ mean in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.


1 Answers

Place this line just below shebang:

shopt -s extglob

to enable extended glob option in your script.

!(logFile.*) is extended glob pattern that requires enabling extglob

like image 58
anubhava Avatar answered Sep 28 '22 09:09

anubhava