0

I'm just trying to echo a variable stored in a file. When issuing the echo $variable command I'm getting a black area with no output. I don't understand why.

Content of file1:

name="Jhon"

My output

enter image description here

Solutions tried:

source /home/ec2-user/file1

After this I get the correct answer. But if I log out from the instance and come back again, it doesn't work.

I tried different type of instances with the same results.

In most of the tutorials on Linux when they execute a variable it pick up from multiple file. Why do I have issue the source command?

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • 2
    If you don't run the name="Jhon" line how do you expect the value to be set? No matter how it is done, that line must be run for the variable to be set. One way is source as you have mentioned. If you want to do it for each shell invocation then put it into your shell's rc file. e.g. ~/.bashrc for bash shell. – kaylum Jan 05 '20 at 03:00

2 Answers2

2

A "variable stored in a file" isn't really a thing. Most kinds of variables exist in the state of a running process (shell or other program). (There's a difference between environment variables, shell variables, etc, but that's not important here.) Each process has its own set of variables (except that copies of environment variables get inherited by subprocesses when they're created).

You can define a variable in a shell process with a command like name="Jhon", but it only defines that variable in that particular shell process, not any other. Also, it's an executable command; the definition only takes place when it's executed (not e.g. when it's sitting in a file), and can be changed later by running some other command like name="Rho" or unset name.

The usual way to define a variable "everywhere" is to put a command to define it in a shell initialization file, like ~/.bashrc. But this definition only gets executed if the shell runs commands from that file when it starts up; for instance, a bash login bash shell will run ~/.bash_profile (or ~/.bash_login or ~/.profile) instead of ~/.bashrc; shells other than bash (like zsh and dash) will run still different init files.

0

for persistence declare variable in rc, or source file to rc

echo 'source /home/ec2-user/file1' >> /home/ec2-user/.bashrc
rho
  • 169