1

So, this question seems a-specific. It is, because I'm not a BASH-programmer, rather a Biologist-turned-writing-some-useful-scripts-for-my-daily-work-scripter. Anyway. Say, I have a for loop, like so:

for CHR $(seq 1 22); do
    echo "Processing chromosome ${CHR}";
done

I used to write `seq 1 22` but now I've learned to write $(seq 1 22). Clearly there is a difference in terms of the way you write it. But what is the difference in terms in computer language and interpretation? Can someone explain that to me?

The other thing I learned by simply doing on the command line on our computer cluster, was to call "i" differently. I used to do: $CHR. But when I'd have a file name sometext_chr to which I'd like to add the number (sometext_chr$CHR) that wouldn't work. What does work is sometext_chr${CHR}. Why is that? Can someone help me explain the difference?

Again, I know the question is a bit a-specific - I simply didn't know how to otherwise frame it - but I hope someone can teach me the differences.

Thanks and best!

Sander

1 Answers1

1

The $(...) can be nested easily, as the parentheses clearly indicate where an expression starts and ends. Using `, nesting is not so simple, as the start and end symbols are the same.

Your second example is probably from memory, because it's incorrect. sometext$chr and sometext${chr} would both work the same way. Perhaps what you really meant was a situation like this:

$chr_sometext
${chr}_sometext

The key point here is that _ is a valid character in a variable name. As a result, $chr_sometext is interpreter as the value of the variable chr_sometext. In ${chr}_sometext the variable is clearly chr, and the _sometext that follows it is a literal string value. Just like if you wrote $chrsometext you wouldn't assume that the chr is somehow special. This is the reason you have to add the clarifying braces.

janos
  • 120,954
  • 29
  • 226
  • 236