0

i am trying to print all parameters in bash script "one by one".
fro example i want to run:
./myscript hello all friends
and see below result:

 hello  
 all  
 friends.  

i wrote below code:

#!/bin/bash
li=$@
for(( j=0;j<$#;j++));
do
    echo ${li[$j]}
done

bug when i run my code it prints all of argument at once:

hello all friends

i know i can do that by changing the for structure to below format:

#!/bin/bash
li=$@
for j in $li;
do
    echo $j
done

but i didn't want to change the code such as above.
please help me.
thank you in advance.

milad
  • 1,854
  • 2
  • 11
  • 27

2 Answers2

1

You can write using echo -n option to skip printing newline at the end.

echo -n ${li[$j]}

Check docs here.

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

Try with this:

#!/bin/bash
li=$@
for(( j=0;j<$#;j++)); do
    printf '%s\n' ${li[$j]}
done

Here you can find some info about formatting: https://wiki.bash-hackers.org/commands/builtin/printf

l.kusiak
  • 16
  • 2