rm !(myfile) does not work on OS X?

2

1

The command works fine on Linux but on OS X Mountain Lion when I'm doing:

rm !(myfile)

bash complains:

bash: !: event not found

Is there any way to do it the same on OS X?

user151851

Posted 2013-01-11T22:32:55.177

Reputation: 125

What are you trying to do, remove a file named !(myfile) ? Or... ? – Kyle Jones – 2013-01-11T22:48:30.387

Answers

3

This is because you haven't set the extglob option, which gives a special meaning to !.

In your Bash, write:

shopt -s extglob

Then, the command should run as expected.

By default, ! expands to the process ID of the most recently executed background (asynchronous) command. With the extglob set, ! can be used for pattern matching, but only in conjunction with parentheses following it ().

You could of course add this line to your ~/.bash_profile to have it set any time you open Terminal.app. OS X by default runs a login shell, so these options should be set in ~/.bash_profile and not ~/.bashrc as you're probably used to from Linux terminal emulators.

slhck

Posted 2013-01-11T22:32:55.177

Reputation: 182 472

"!" has special meaning for command history, extglob enables its use for negative pattern matching which can override that. The error observed is due to the history feature (a minor irritation being that the errant command is not added to your command history). – mr.spuratic – 2013-01-11T22:58:00.500

The pid of the last background process is $!. Just ! isn't expanded to anything by default by bash. – Lri – 2013-01-12T09:38:14.173

@Lauri, yes, in combination with $, as explained in the Bash reference manual. Maybe that part wasn't clear. – slhck – 2013-01-12T10:08:58.027