0
#!/bin/bash
if [ -f "$1" ] #parameter is file name, if i exists...
then
    VARIABLE=`cat "$1"` #assign what's inside into VARIABLE
fi

I've tried bash -x script_01.sh "file" and the tracing works:

+ '[' -f file ']'
++ cat file
+ VARIABLE='Wednesday, November  4, 2015 04:45:47 PM CET'

But the problem is that when I echo $VARIABLE, it's empty. Do you guys have any tips on how to make it work? Thank you.

2
  • It works for me. I added echo $VARIABLE to the end of your script and saved it under script.sh. If I run bash script.sh script.sh, it echoes the contents of the script as expected. Commented Nov 4, 2015 at 16:04
  • Yeah, when I add echo at the end of the script, it works. But outside of the script it doesn't. I guess it's in the other process that I'm running. Commented Nov 4, 2015 at 16:28

1 Answer 1

2

VARIABLE is set in the process that runs the script, not the process which called the script. If you want to set it in your current environment, you need to source the file instead.

. script_01.sh "file"
Sign up to request clarification or add additional context in comments.

4 Comments

So if I understood correctly, there are two bashes, bash1: the one I'm using right now and bash2: the one that runs the script. So VARIABLE will be set to cat file only in bash2 while in bash1 it won't be anything yet? I don't understand the second path. I did use "file" as parameter, right?
Right; variables are "local" to the script/shell in which they run. So although VARIABLE is correctly set within the run of script_01.sh, it goes away once that script exits.
So in order to get it out of the scripting I would have to add "export VARIABLE"?
No, export is a one-way process, for passing information from the parent to its child. There is no way (by design) for a child to affect the environment of its parent, which is why you have to source the file as I've shown so that the code executes in the same process.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.