课程: Learning Linux Shell Scripting

Reading environment variables

- [Man] Environment variables are like our own, except they are defined for us, by the system. They allow us to know things about our script's environment. Let's check them out with a bit of code. So we'll say, touch vars dot sh. To a change mode. Seven five five vars dot sh. And atom vars dot sh. Add our old friend, the shabang. Let's check out three environment variables. So we're gonna check out the PATH, the term and the editor. We'll just echo them out to the screen. So we'll say, echo the PATH is dollar sign PATH, so notice that they're just like our own internal variables. Except, these are defined elsewhere, they're actually defined in other scripts that run before our stuff executes. And we're gonna say echo the terminal is, and this is dollar sign term. And the final one that we'll check our right now, is gonna be echo the editor is, and this is dollar sign editor. So let's do a control s, go to the terminal, and execute this script. And we do var sh. Or if we spell it correctly, vars dot sh. We get the PATH and we get the very long string. We get the terminal is xterm dash 256 color. And we notice that the editor isn't set. This is usually something that developers will set in their bash underscore profile settings. So let's go back into atom. Now not all values are used by all systems. If not said, it will hold an empty string. And we can detect this though, using an IF statement, so let's go ahead and check that editor value and we'll say, if space minus z, this checks for an empty string. And we'll say editor. Again, note the spacing. And we'll say then echo the editor variable is not set. And give our fi, and do a control s again. And when we run this modification, now we see that we get the message down here, that the editor is not set. We got one last trick. And we can change the value of any of the environment variables in our script, but its value will revert when the script exits. So let's go ahead and change the PATH. And so what we'll do is we'll say that, PATH equals forward slash bob. And then when we say echo again, and again we'll say, the PATH is dollar sign PATH. And do a control s. Go back to the terminal, execute the script once more. And you notice that the very last line is, the PATH is, and it says bob. But if from here, and the terminal I do an echo dollar sign PATH, the PATH has been restored. So you can change these and they'll affect your script, but environment variables always revert to the way that they were set before your script ran.

内容