1

I have a script that outputs a list of env vars like:

THING=one
ANOTHER_THING=two
A_PATH="path/to a/directory"

When I try to export these env vars as export `./script`, the A_PATH env var exports as path/to.

If I export the list as plain text like: export THING=one ANOTHER_THING=two A_PATH="path/to a/directory", it works just fine.

I'm stumped as to why bash treats the white space in the A_PATH differently in these two cases. I've tried various attempts at escaping the whitespace and I've even tried exporting line by line, but in every case it sees the whitespace as a delimiter rather than as a part of the path string.

emery098
  • 11
  • 2
  • 3
    Because you have not quoted the command substitution, [Word Splitting](https://www.gnu.org/software/bash/manual/bash.html#Word-Splitting) will happen – glenn jackman Jul 27 '21 at 21:33

2 Answers2

1

why bash treats the white space in the A_PATH differently in these two cases

The result of command substitution `...` undergoes word splitting. Do not use ` backticks - use $(....) instead. Check your scripts with shellcheck.net .

Spaces inside string around double quotes are literally preserved. See quoting.

If the file has proper correct shell syntax, and it's meant to be sourced and support shell-ish execution, see https://unix.stackexchange.com/questions/614568/is-is-possible-to-export-all-variables-obtained-from-sourcing-a-file . If the file contains = separated variable name and optionally quoted string with custom syntax, write a parser for the file for that syntax - see ex. Parsing variables from config file in Bash for a stub to get started.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

Without the actual code, it is difficult to understand what is going on. But one workaround that might solve your problem is to output the export command and evaluate it.

Example (script.sh):

#!/bin/bash

echo "export THING=one"
echo "export ANOTHER_THING=two"
echo "export A_PATH='path/to a/directory'"
eval $(./script.sh)
Carlos Marx
  • 496
  • 1
  • 6
  • 13