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.

2
  • stackoverflow.com/questions/8467424/… Commented Feb 22, 2019 at 8:19
  • didn't work yet. it prints all elements and then print a new line Commented Feb 22, 2019 at 8:21

2 Answers 2

1

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

echo -n ${li[$j]}

Check docs here.

Sign up to request clarification or add additional context in comments.

1 Comment

didn't work, i want to have new line after any word but it doesn't do that
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

1 Comment

it works fine, thank you. but i have a question: why i can't do that by echo?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.