-1

I have two scripts in the same directory:

latlong.sh

#!/bin/sh
set latlong 'x.xxxxxx:x.xxxxxx'

autostart_once.sh

#!/bin/sh
. ./latlong.sh
# some start up commands
redshift-gtk -l $latlong -t 6500:3600 &

However, running autostart_once.sh above will yield an error. It seems like even after sourcing the latlong script the latlong variable is still empty (I have made sure the working directory is where latlong.sh is). However if I run . ./latlong.sh in a terminal running a fish shell and then echo $latlong the variable is set correctly. What could be happening here?

A few things:

  1. I don't want to be able to access the variable outside the autostart script.
  2. The reason why I am putting the latlong variable to another file is that I encrypt that file before pushing it to a dotfiles repository, but I do not want to encrypt the startup file so that other people can use it as well.
SunnyMonster
  • 500
  • 5
  • 14

1 Answers1

2

The . in . ./latlong.sh is also known as source in some shells. [0]

What it does is tell the current shell to run the given script in the current shell.

That means this in a /bin/sh script will run latlong.sh with /bin/sh, no matter the shebang, and so it will run

set latlong 'x.xxxxxx:x.xxxxxx'

which will set the positional arguments to latlong and x.xxxxxx:x.xxxxxx. It's syntactically valid but means something entirely different in /bin/sh from what it means in fish. And when you run . ./latlong.sh in fish, that fish will read it and interpret set as the fish builtin.

In short: Your simplest solution here is to write both scripts in the same language. This will allow you to source them in the same shell, keeping the variables intact.

If your latlong.sh is as trivial as the example you've shown here, that's easy:

latlong=x.xxxxxx:x.xxxxxx

Or you could choose a data format like csv or json or whathaveyou and find ways to load that into whatever shell.

Or you could attempt the same thing direnv does, which is run the script in a defined shell (bash in their case) and then diff the environment variables to apply them in the user's shell.

[0]: sadly this isn't required by posix and so we're often stuck with the unreadable and easy to miss . name

faho
  • 14,470
  • 2
  • 37
  • 47