How to Include File in a Bash Shell Script

How to include file in a bash shell script

Simply put inside your script :

source FILE

Or

. FILE # POSIX compliant
$ LANG=C help source
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.

How best to include other scripts?

I tend to make my scripts all be relative to one another.
That way I can use dirname:

#!/bin/sh

my_dir="$(dirname "$0")"

"$my_dir/other_script.sh"

how to include a file containing variables in a shell script

It depends which shell, but one of these two usually works:

. var

or

source var

I'm not sure about ksh, but I'd imagine both would work.

include file in bash script

You are invoking bash as /bin/sh which puts bash into sh-compatibility mode. The POSIX standard says that:

If file does not contain a slash, the shell shall use the search path specified by PATH to find the directory containing file.

Which means that the current directory will not be searched unless it is part of $PATH:

$ /bin/sh -c '. test.sh'
/bin/sh: 1: .: t.sh: not found

$ /bin/sh -c 'PATH=".:$PATH"; . test.sh'
$

bash, however, seems to search the current directory:

$ /bin/bash -c '. test.sh'
$

Common include file between shell and makefile

Try this:

eval "$(cat makevars.inc | tr -d '(:)')"
echo "$MY_LIB"

This loads the text of the target include file into memory, erases all colons and parentheses from it and then executes the result.

Include script only once in shell script

Perhaps you can try using Shell Script Loader for that. See a post about it in a famous similar thread: https://stackoverflow.com/a/3692080/445221.

How can I reference a file for variables using Bash?

The short answer

Use the source command.


An example using source

For example:

config.sh

#!/usr/bin/env bash
production="liveschool_joe"
playschool="playschool_joe"
echo $playschool

script.sh

#!/usr/bin/env bash
source config.sh
echo $production

Note that the output from sh ./script.sh in this example is:

~$ sh ./script.sh 
playschool_joe
liveschool_joe

This is because the source command actually runs the program. Everything in config.sh is executed.


Another way

You could use the built-in export command and getting and setting "environment variables" can also accomplish this.

Running export and echo $ENV should be all you need to know about accessing variables. Accessing environment variables is done the same way as a local variable.

To set them, say:

export variable=value

at the command line. All scripts will be able to access this value.



Related Topics



Leave a reply



Submit