Prevents execution of a command from a source'd file in Bash

advertisements

For security purposes, how can I prevent a command being executed in a file that is source'd? For example:

#!/bin/sh
source file.cfg

Wanted:

get="value"

Unintended:

command


You could use a mechanism like in Python. Define variables and/or functions and put executable commands into a conditional block:

#!/bin/bash

# Variables and functions comes here
a=1
b=2

function foo() {
    echo "bar"
}

# Put executable commands here
if [ "$0" = "$BASH_SOURCE" ] ; then
    foo
fi

If you chmod +x the file and run it or run it through bash file.sh the executable commands in the conditional statement will get executed. If you source the file only variables and functions will get imported.