Reputation: 13
So im learning shell script in school right now and i was working on this assignment and was stuck. Our prof/TA will be testing the answers to this questions by running simple commands like:
echo <random numbers>| sh question1
where random numbers can be anything. ie
echo 7 8| sh question1
So im not trying to get the answer to the assignment question but i have an idea of how to go about solving the question but, im hitting a bit of a snag out the gate.
I was trying something like this at the begining of my question1
file:
VAR1=tr -d [" "]
my thought process for this is that, i am trying to delete any spaces between the numbers it gives me and putting it in to a variable. but now im wondering how i can iterate over numbers in the variable
im probably 2-3 weeks into shell scripting and i learned python first so im not even sure if i can even iterate over it. But i thought there could be a way where i take the contents of a file, iterate over them and can access one char or integer at a time. is this even possible? i spent a lot of time trying to find a solution.
Any help would be great!
Upvotes: 0
Views: 820
Reputation: 531878
An alternative approach to Vorsprung's answer would be to read a single line of input in your script, then use that to set that script's arguments. At the top of your script:
read line
set -- $line
Then you can use the same for loop:
for i in $*; do
echo $i
done
This makes the same assumption as Vorsprung: the input will be a single line of space-separated values. If that assumption is false, I hope your instructors will be more specific about the type of input your script should be able to accept.
Upvotes: 0
Reputation: 34377
Does this example help?
for i in $*
do
echo $i
done
$*
is a list of the command line args, so running this as ./file.sh a b c
will print a b c
Your input is apparently appearing on a pipe so next do this
echo 1 2 3 | xargs ./file.sh
xargs
converts piped values into shell program parameter values
Upvotes: 3