Reputation: 43
What I'm attempting to do is receive values from the command line (instead of using the read method and asking the user to enter the values and/or file names in multiple steps).
./hello.sh 5 15 <file_name.txt
I have heard that simply using an array can help do the same, but I am not able to-
Avoid printing
5 15
on the next line
Since 5 and 15 are being printed, I'd expect the string 'abcdefgh' (contents of file_name.txt) to be printed; however, the output stops at
5 15
I would really appreciate it if someone could point out why my code isn't sufficient, and if possible, point me in the direction of some learning resources to broaden my knowledge of this concept.
Here is the code:
#! /usr/bin/bash
echo "$@"
I am simply testing things out (wanted to print out the variables before doing anything with and to them).
Upvotes: 1
Views: 654
Reputation: 72
Will this work?
./hello.sh 5 15 `catfile_name.txt`
And update hello.sh
to:
#! /usr/bin/bash
shift 2
echo $@
Upvotes: 1
Reputation: 140980
<file_name.txt
is a redirection. It is not passed as a parameter. The parameters of the script are 5
and 15
. The <
redirects the file file_name.txt
to standard input stdin of the script. You can read from stdin with for example cat
.
#!/usr/bin/bash
echo "$@" # outputs parameters of the script joined with spaces
cat # redirects standard input to standard output, i.e. reads from the fiel
why my code isn't sufficient
Your script is not reading from the file, so the content of the file is ignored.
point me in the direction of some learning resources
File descriptors and redirections and standard streams are basic tools in shell - you should learn about them in any shell and linux introduction. My 5 min google search resulted in this link https://www.digitalocean.com/community/tutorials/an-introduction-to-linux-i-o-redirection , which looks like some introduction to the topic.
Upvotes: 1
Reputation: 2654
Here is a more generic solution. It looks at each input parameter in turn. If it is a valid file, it outputs the contents of the file. Otherwise if just prints the parameter.
#! /usr/bin/bash
for $parameter in "${@}"; do # Quotation marks avoid splitting parameters with spaces.
if [ -f $parameter ]; then # '-f {value}' tests if {value} is a file.
cat $parameter
else
echo $parameter # You could also use 'echo -n ...' to skip newlines.
fi
done
Upvotes: 0