Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over positional parameters in a Bash script?

Tags:

bash

scripting

Where am I going wrong?

I have some files as follows:

filename_tau.txt
filename_xhpl.txt
filename_fft.txt
filename_PMB_MPI.txt
filename_mpi_tile_io.txt

I pass tau, xhpl, fft, mpi_tile_io and PMB_MPI as positional parameters to script as follows:

./script.sh tau xhpl mpi_tile_io fft PMB_MPI

I want grep to search inside a loop, first searching tau, xhpl and so on..

point=$1     #initially points to first parameter
i="0"
while [$i -le 4]
do
  grep "$str" ${filename}${point}.txt
  i=$[$i+1]
  point=$i     #increment count to point to next positional parameter
done
like image 562
Sharat Chandra Avatar asked Nov 20 '09 08:11

Sharat Chandra


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is positional parameters in bash?

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0 . Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command.

What are positional parameters in shell script?

A positional parameter is a variable within a shell program; its value is set from an argument specified on the command line that invokes the program. Positional parameters are numbered and are referred to with a preceding ``$'': $1, $2, $3, and so on. A shell program may reference up to nine positional parameters.


1 Answers

Set up your for loop like this. With this syntax, the loop iterates over the positional parameters, assigning each one to 'point' in turn.

for point; do
  grep "$str" ${filename}${point}.txt 
done
like image 60
Steve K Avatar answered Nov 12 '22 09:11

Steve K