Noor Noor - 11 days ago 7
Linux Question

Pass string to script

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?

Answer

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.