41

For example this line fails:

$ nohup for i in mydir/*.fasta; do ./myscript.sh "$i"; done > output.txt&
-bash: syntax error near unexpected token `do

What's the right way to do it?

neversaint
  • 60,904
  • 137
  • 310
  • 477
  • The "why" is that nohup executes its arguments with `execv()`, and `execv()` takes an argument vector which is passed directly to the kernel, not going through any shell. Thus, if you want a shell, you need to tell nohup to execute one yourself. – Charles Duffy Feb 27 '14 at 19:36

3 Answers3

100

Because 'nohup' expects a single-word command and its arguments - not a shell loop construct. You'd have to use:

nohup sh -c 'for i in mydir/*.fasta; do ./myscript.sh "$i"; done >output.txt' &
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    Will this be writing over output.txt for each file? If there is important information in there that you do not want overwritten, I would use `>>` instead of `>`. – Climbs_lika_Spyder Feb 01 '15 at 12:04
  • If I have important data in `output.txt`, I would not run the output of a program into it even in append mode. I would create a new file, and only when I was satisfied that the new data was what I wanted would I append it to the master file. YMMV, of course. – Jonathan Leffler Feb 01 '15 at 14:53
  • @JonathanLeffler that doesn't answer the question though. I believe this only truncates once. – Brian Hannay Sep 05 '17 at 16:26
11

For me, Jonathan's solution does not redirect correctly to output.txt. This one works better:

nohup bash -c 'for i in mydir/*.fasta; do ./myscript.sh "$i"; done' > output.txt &

Martin
  • 361
  • 4
  • 12
10

You can do it on one line, but you might want to do it tomorrow too.

$ cat loopy.sh 
#!/bin/sh
# a line of text describing what this task does
for i in mydir/*.fast ; do
    ./myscript.sh "$i"
done > output.txt
$ chmod +x loopy.sh
$ nohup loopy.sh &
msw
  • 42,753
  • 9
  • 87
  • 112
  • 4
    Unless `loopy.sh` is in the path, you need to invoke it like `./loopy.sh`, at least on this Red Hat system I just tried with. – tshepang Apr 29 '13 at 14:51