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.

  • 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. – buff Nov 04 '15 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. – Hichigaya Hachiman Nov 04 '15 at 16:28

1 Answers1

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"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 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? – Hichigaya Hachiman Nov 04 '15 at 16:11
  • 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. – chepner Nov 04 '15 at 16:41
  • So in order to get it out of the scripting I would have to add "export VARIABLE"? – Hichigaya Hachiman Nov 04 '15 at 17:01
  • 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. – chepner Nov 04 '15 at 17:10