5

Please tell me why I couldn't print variable value.

# chmod 777 chkscript.sh
# ./chkscript.sh

chkscript.sh file content

variable = "This is variable"

echo "$variable"

echo "Hello World "

Output :

# ./chkscript.sh
./chkscript.sh: line 5: variable: command not found

Hello World
#

P.S : And sometimes

 variable1 = "/home/files" --- which is location if I try to print nothing gets printed.
 echo "$variable"

2 Answers 2

13

In shell, spaces are not allowed on either side of the = in a variable assignment.

Try this instead:

variable="This is a variable"

If you leave a space before the =, the shell parses the token before it as a command or function name, which is why you see the "command not found" message.

4
  • variable="This is variable" echo"$variable" changed like this but no use.Thanks for reply.
    – sunleo
    Jul 2, 2014 at 11:53
  • 1
    You still need the space after echo - if you omit it, the shell expands what's in $variable and then tries to find the command that is called (in this example) echoThis with the arguments is variable. Almost certainly NOT what you want!
    – D_Bye
    Jul 2, 2014 at 11:55
  • 1
    Thanks for the insight on that. I am still learning shell scripting as I go :)
    – ryekayo
    Jul 2, 2014 at 11:56
  • Finally fixed this Thanks you.It is really hard to fix space related thing here.Thanks for all your replys.
    – sunleo
    Jul 2, 2014 at 11:57
-1

I had a similar problem, and I did this:

#!/bin/sh
my_chars='This is test' ;
echo $my_chars
~

Now

$ ./test_chars.sh
This is test

This works

1
  • This doesn't really explain what was wrong.
    – X Tian
    Aug 23, 2016 at 13:37

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.