Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to write a script which reads a file and executes a command for each row in the file. This command contains a variable for which we need to pass each row in the file.

File has only one column and close to 500 rows.

share|improve this question

try this:

#!/bin/sh
if [ -f $1 ]; then
        while read line; do
                ./execute.sh $line;
        done < "$1"
fi

To execute, ./script.sh datafile.txt

share|improve this answer
    
I am assuming $1 is the filename right? or a variable declared like $1=/home/file.txt ?? – Guest123 May 6 '13 at 4:45
    
Yes, $1 is the first argument passed to the shell script from the command line, so datafile.txt in the example ./script.sh datafile.txt. – Kevin Fegan May 6 '13 at 4:53
    
Correct. Just define your script as execute.sh, and put those file with aforementioned rows at datafile.txt. You should be able to modify that script to suit your need. $1 is variable for first parameter, in this case, your datafile that contained those parameters. – prd May 6 '13 at 5:02
    
Thanks a lot Rudy...it worked – Guest123 May 6 '13 at 7:16
    
Just accept the answer :D – prd May 6 '13 at 10:25

The xargs command with the -I option does exactly that:

xargs -I {} yourcommand ... {} ... < yourinputfile

where ... are the remaining arguments of your command (if any). The {} part is replaced by every line from yourinputfile.

share|improve this answer

Your question isn't clear but if you want to write a script to execute another file, Try below command:

if [ -f /home/sepahrad/MyFile ]; then

./MyFile

fi

When you execute your file it executes MyFile commands one by one. You have to replace your file address instead of /home/sepahrad/MyFile.

share|improve this answer
    
I want to send each row in this file as a variable into the command...example: command $/home/sepahrad/MyFile -c username -p password – Guest123 May 6 '13 at 4:39
    
Now how do i pass each row into the command...else shall i use for loop in this case? – Guest123 May 6 '13 at 4:40
    
Oh i got it, Try awk command, $0 in awk command means all of line, and you know that awk command check each line of file, Or use While to read each line. – Sepahrad Salour May 6 '13 at 5:30
    
Salour... i tried using this awk for a different purpose and it worked – Guest123 May 14 '13 at 5:44
    
Good news ... :) – Sepahrad Salour May 14 '13 at 6:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .