Score:0

Script runs echo normally, but prints nothing for looped echo

cn flag

I'm trying to write a script that opens a terminal and loops echo in it. I have the following.

#!/usr/bin/bash

gnome-terminal -- /bin/bash -c "for i in 1 2 3; do echo $i; done; exec bash"

When I run this script, it shows three blank lines and then executes bash. However, if I run for i in 1 2 3; do echo $i; done; exec bash in a terminal it prints normally. Also, if I write the following it prints hello normally too. Therefore, I believe it's an issue with the for loop.

#!/usr/bin/bash

gnome-terminal -- /bin/bash -c "echo hello"

I couldn't find anyone with a similar issue.

cn flag
Ray
Why do you have `exec bash` at the end? I'm not sure if you want to run a loop within bash and then start another bash shell... Indeed, something is wrong with your code, but I can't put my finger on it... You're getting 3 blank lines because it is the value of `$i`. If, let's say, you put `i=10` and then run the loop, you'll get three `10` printed out, I think.
bac0n avatar
cn flag
you need single quotes or `$i` will evaluate, therefore ... empty lines
matticebox avatar
cn flag
@Ray I have `exec bash` at the end so I can look at the terminal after it loops echo. I was using sleep before, but I figured starting another bash shell would be easier. I'm a noob and don't really understand what you mean by `i=10`, but if i put `10` in place of `$i` it does indeed print `10` three times. It just doesn't make sense to me because when I run the code with `$i` in a terminal, it prints `1`, then `2`, then `3`. For example, `for i in hello; do echo $i; done` will print `hello` in a terminal.
matticebox avatar
cn flag
@bac0n I tried `gnome-terminal -- /bin/bash -c "for i in 1 2 3; do echo '$i'; done; exec bash"` and it still shows empty lines, unless I'm not noticing something else I've done wrong.
bac0n avatar
cn flag
no, `/bin/bash -c 'for i in 1 2 3; do echo $i; done; exec bash'`
matticebox avatar
cn flag
@bac0n It worked, thanks. But I don't understand what exactly is going on... I thought the usage of double and single quotes was just so you could have one inside the other.
Artur Meinild avatar
vn flag
[See here](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash).
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.