C system function causes error 'sh: Syntax err

2019-08-21 14:21发布

问题:

I wrote a simple program in C on Linux to delete all the files in a directory except one called svn like this:

  1 #include <stdio.h>
  2 
  3 int main()
  4 {
  5     system("rm !(svn)");
  6     return 0;
  7 }

But when I compile and run it, the terminal says: sh: Syntax error: "(" unexpected

However, when I type and run the command in the terminal directly, all things are done correctly. Any ideas?

回答1:

The answer is don't use system. Use the Linux system calls to list the files in the directory and remove them using unlink(). Something like:

DIR* dirHandle = opendir(dirName);
struct dirent* dirEntry;
while ((dirEntry = readdir(dirHandle)) != NULL)
{
    if (strcmp(dirEntry->d_name, "svn") != 0)
    {
        unlink(dirEntry->d_name);
    }
}

Warning: all error handling omitted, not compiled and tested, readdir might return . and .. which also need to be not deleted.



回答2:

You will probably need to use this:

system("/bin/bash -c 'rm !(svn)'")

or possibly:

system("/bin/bash -O extglob -c 'rm !(svn)'")

or:

system("find . -maxdepth 1 ! -name 'svn' -delete")

or similar.

But it's probably better to use JeremyP's answer.



回答3:

You must use sh shell syntax, you are not doing this.



回答4:

I think I would just add the shell to the system command:

system("/bin/csh rm !(svn)");

or whatever shell you use.



回答5:

Workaround: Move file outside directory (f. e. in /tmp or ..), delete all, move it back (do it using several system() calls).

Another approach:

find . -prune ! -name svn | xargs /bin/rm -f