0

I have a simple bash script:

#!/bin/bash

export MONGOMS_DOWNLOAD_URL="https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1804-4.2.8.tgz"
export MONGOMS_VERSION="4.2.8"

but when i run this './preinstall.sh' and then echo $MONGOMS_VERSION the var is not set.

If i export these vars directly in the terminal there is no issue.

https://stackoverflow.com/questions/496702/can-a-shell-script-set-environment-variables-of-the-calling-shell#answer-496777 According to this post, a shell script has read only access to the parent and any vars set will be lost.

Is there a way around this?

John
  • 887
  • 4
  • 15
  • 25

2 Answers2

1

Use:

source ./preinstall.sh

or for better portability:

. preinstall.sh

source is a synonym for dot/period '.' in bash, but not in POSIX sh, so for maximum compatibility use the period.

. (source or dot operator)

Read and execute commands from the filename argument in the current shell context.

See: . (source or dot operator)

Kate
  • 487
  • 3
  • 8
1

You need to source ./preinstall.sh. There are two ways to do that:

source ./preinstall.sh

or

. ./preinstall.sh

Bash, as does ksh and zsh supports both . and source. It reads and executes the contents of the specified file in the current shell as opposed to in a new process.

Using the bash shell:

$ type source
source is a shell builtin
$ type .
. is a shell builtin
$ source --help
source: source filename [arguments]
    Execute commands from a file in the current shell.
    
    Read and execute commands from FILENAME in the current shell.  The
    entries in $PATH are used to find the directory containing FILENAME.
    If any ARGUMENTS are supplied, they become the positional parameters
    when FILENAME is executed.
    
    Exit Status:
    Returns the status of the last command executed in FILENAME; fails if
    FILENAME cannot be read.
$

POSIX specifies the dot (.) special builtin but is silent about source. From the standard:

NAME
dot - execute commands in the current environment
SYNOPSIS
. file

DESCRIPTION
The shell shall execute commands from the file in the current environment.

If file does not contain a <slash>, the shell shall use the search path specified by PATH to find the directory containing file. Unlike normal command search, however, the file searched for by the dot utility need not be executable. If no readable file is found, a non-interactive shell shall abort; an interactive shell shall write a diagnostic message to standard error, but this condition shall not be considered a syntax error.

OPTIONS
None.

For maximum shell script portability you should only use the dot command with no arguments.

As an aside, I recommend you use absolute paths instead of relative paths if you are sourcing from scripts whose location may change.

fpmurphy
  • 841
  • 6
  • 13