-1

So I have to create a script that does something like this:

./scriptname.sh 1 2 4 carrot apple
1. 1
2. 2
3. 4
4. carrot
5. apple

Show them in a counter no matter how many arguments I give it.

I've tried doing this, but it doesn't work:

#!/bin/bash
k=0;
while [$k -lt $#]
do
    k=$((k+1))
done
echo "$k"
exit 0
0

Your while loop never touches the arguments passed, it simply uses the variable $# which is the total number of arguments - never the arguments themselves.

If I were given this assignment, I would do something like this:

#!/bin/bash

# Get no of args
noArgs=$#
# Save arguments in array
myArr=("$@")

# Loop the array
for ((i=0; i<$noArgs; i++)); do
    echo $((i+1)). ${myArr[$i]}
done

exit 0

A couple of examples:

./printArgs.sh foo bar baz
1. foo
2. bar
3. baz

./printArgs.sh 1 2 napalm death
1. 1
2. 2
3. napalm
4. death

./printArgs.sh seasons in the abyss
1. seasons
2. in
3. the
4. abyss
0

one possible answer:

#!/bin/bash
k=0;
while [ $# -gt 0 ]; 
do
    let k=k+1
    echo "$k $1"
    shift
done
exit 0
  • what does -gt 0 mean? – dndwanted Nov 20 '16 at 17:18
  • -gt 0 : "greater than zero" (since shift removes the inputs one after one) – tonioc Nov 20 '16 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.