3

I have a code like this

#! /bin/bash

$version = "1.0";
$preffix = "ApplicationName.";

for f in pack*;
do
    echo "bla bla bla" > myFile.txt
    echo $preffix >> myFile.txt
    echo "more stuff" >> myFile.txt
    echo $version >> myFile.txt
done;

the output is

bla bla bla

more stuff

$version and $preffix are not added to myFile.txt... why?

  • 3
    Surely you got a pair of bash: =: command not found errors? You really should pay attention to them. – Kevin Nov 22 '12 at 18:16
5

This program will work where yours doesn't:

#!/bin/bash

version="1.0";
preffix="ApplicationName.";

for f in pack*;
do
    echo "bla bla bla" > myFile.txt
    echo $preffix >> myFile.txt
    echo "more stuff" >> myFile.txt
    echo $version >> myFile.txt
done;

Your affection for spaces makes your program more readable, and also makes it not work.

Also, while it doesn't matter for this program, it would be a really good idea to do this:

#!/bin/bash

version="1.0";
preffix="ApplicationName.";

for f in pack*;
do
    echo "bla bla bla" > myFile.txt
    echo "$preffix" >> myFile.txt
    echo "more stuff" >> myFile.txt
    echo "$version" >> myFile.txt
done;

This is because if you did something like:

version='1  2'

in your original program, you would end up with a somewhat unexpected result. Putting the quotes around your variables is a really good idea to prevent mysterious errors like that.

  • 2
    Quoting the variables in this case will only keep any whitespace from being collapsed; bash only interprets variables once, so a='$(ls -l)'; echo $a; echo "$a" will print $(ls -l) twice, it doesn't go back and expand it again. – Kevin Nov 22 '12 at 18:14
  • @Kevin: Oh, that's very interesting to know. Well, reduces the potential security issues of not quoting properly. I should've tested before I said something. I modified my answer accordingly. – Omnifarious Nov 22 '12 at 19:48
6

The $ sign in front of variables is used to read them.

If you want to assign them, you have to leave out the $ sign, i.e.:

version="1.0"
preffix="ApplicationName."

Also, the ; are not required at the end of the assignment lines.

  • thanks. I did the changes but the problem persists. – SpaceDog Nov 22 '12 at 17:55
  • You should also remove space around =. Just like in above answer. – Lukasz Stelmach Nov 22 '12 at 17:59
  • Also, just because it's good practice echo "$preffix" >>myFile.txt and echo "$version" >>myFile.txt. – Omnifarious Nov 22 '12 at 18:00

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.