How to remove a file from fortran code?

I need to delete a file from Fortran code. I am on ubuntu 12.04, x86_64 . I do not understand why the procedure described below does not work. Please help me clarify the situation (in fact, on some systems it works, but not on mine).

There is another way: I can directly invoke the unix rm -f file command, but I would like to know what is wrong with my method. Thanks.

Step 1. Make a simple script del.sh and put it in ~ / bin

 $ cat del.sh [ $# -ge 1 ] && rm -f $1 $ chmod u+x del.sh; mv del.sh ~/bin 

Step 2. Code Fortran, del.for:

 character*100 cmd character*30 file call getarg(1,file) write(cmd,100) file 100 format('source del.sh ',a30) call system(cmd) end 

Step 3. Compile and run:

 $ ifort -o del del.for $ ./del file 

Results:

 sh: 1: source: not found 

What's wrong? The simple "del.sh source file" works, but not from Fortran code ... this is confusing.

From Fortran Code:

 100 format('del.sh ',a30) 100 format('bash del.sh ',a30) 

works fine but

 100 format('sh del.sh ',a30) 

does not work. I have bash installed but no csh . Thanks.

+6
source share
5 answers

Why not let Fortran do the work for you? This code is portable (compare chat comment):

 open(unit=1234, iostat=stat, file=file, status='old') if (stat == 0) close(1234, status='delete') 
+29
source

source is a built-in shell that loads another script in the current process (as opposed to running it in a subprocess).

You do not need source when calling a script from Fortran, as you know. Both del.sh and bash del.sh , and any of them reflects how you should do this.

+2
source

A system call invokes a shell to execute your command, whose shell is system / environment dependent. Since you get sh: 1: source: not found , the called shell does not understand the source command, which is bash built-in. In Ubuntu, by default /bin/sh bound to /bin/dash , not /bin/bash , and dash does not understand source . Use instead . (portable) inline instead of source :

 100 format('. del.sh ',a30) 

should work if del.sh is in your $PATH .

This is why I think they will all work:

 100 format('sh del.sh ',a30) 100 format('bash del.sh ',a30) 100 format('del.sh ',a30) 

But is it different with you? In this case, it hits me :)

+2
source

So, in your shell script you will not specify the program in the first line. Try adding:

 #!/bin/bash 

like the very first line in del.sh. When bash runs it without it, it can run the script with / bin / sh, not / bin / bash, as you expected. (I cannot confirm right now, but I know that I had problems in the past if I use bash-specific code, but forget to put shebang at the top.) When bash starts it with this line, it will see that it should be done using bash. Since your code shows that it immediately calls it as a bash argument, I would say that this should fix your problem. All the best.

+1
source

Try

 call system(trim(cmd)) 
-1
source

Source: https://habr.com/ru/post/953369/


All Articles