Matam Matam - 1 year ago 37
Bash Question

Reading parameters from a file consisting one line in a shell script

So I have this shell script:

#!/bin/bash -xv

#filename: testScript

echo $#

It should print the number of parameters I receive from a text file.

I have a text file(named: file.txt) with one line:

I am a proud sentence

The output should be, as I understood, 5. Since there are 5 words, there are 5 parameters.

I try to run it by:

chmod +x ./testScript.txt

./testScript.txt < ./file.txt > output.txt

But I seem to get in output.txt 0, as if there were no parameters. I really barely understand when do I use $1 $2 to approach parameters, and how to actually send parameters into a script.
Should I use pipe? Can it be implented with pipe, anyways?

Also. When a text file is passed to a script. Is $1 the text file's name? Will
echo $1
for the above example, with only the specified arguments done?


< ./file.txt sets standard input of the command line to the content of the file.

read needs to be used to read standard input.

Maybe this script is closer to your needs

#/bin/bash --
printf "%d\n" $#

call it with

./testScript.txt $(cat ./file.txt) > output.txt

$(...) makes the shell ececute the command first. The line in the file is then passed as parameters to the script


Otherwise if you use

 ./testScript.txt ./file.txt

Then $1 is equal to ./file.txt