-2

I have a script, download, that takes a string and checks if a file has the filename of the string. If it doesn't, it then downloads it. All the filenames are in a file.

This command is not working:

cat filenames | ./download

Download source:

filename=$1
if [ ! -f $1 ];
then
        wget -q http://www.example.com/nature/life/${filename}.rdf
fi

Sample filename file:

file1
file2
file3
file4

How do I pass the command output from the cat to the download script?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Noor
  • 19,638
  • 38
  • 136
  • 254

2 Answers2

2

In your script $1 is the positional arg on the command line. ./download somefile would work, but cat filename | ./download streams the data into download, which you ignore.

You should read the advanced bash scripting guide, which will give you a good base for how bash scripting works. To fix this, change your command to:

cat filename | xargs -n 1 ./download

This will run ./download for each filename in your list. However, the filenames may have spaces or other special characters in them, which would break your script. You should look into alternatives ways of doing this, to avoid these problems.

Specifically, use a while loop to read your file. This properly escapes your filenames on each line, if they were input into the file correctly. That way, you avoid the problems cat would have with filenames like: fi/\nle.

Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
1

You can pass a filename to a file that contains file names to your script:

./download filenames

And then loop through file names from the file name in $1:

$!/bin/bash
# Do sanity check

fname=$1

for f in $(<$fname); do
   if [ ! -f "$f.rdf" ]; then
     wget -q http://www.example.com/nature/life/${f}.rdf
   fi
done
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anubhava
  • 761,203
  • 64
  • 569
  • 643