1

I'd like to know if it's possible to source a file in Bash (using . filename or source filename) but only inherit environment variables and functions from it, ignoring any other lines.

For example, a file to source might contain the following lines:

my_var="Something" do_something_quickly() { some_command another_command } another_var="Something-Else" some_command final_var="FinalString" 

I'd like to be able to source this and other similar files, but only source the variables and functions from it, so any other lines (like some_command which could be an arbitrary and possibly malicious command) are ignored completely. Is there a way to achieve this?

1
  • Why not just copy what you want from the file, put it in a shell init file like .bashrc or .ksh or that for whatever shell that you are using, and have it be sourced when you start a new shell? That would be far easier.CommentedDec 12, 2021 at 23:34

1 Answer 1

1

I don't think what you want is possible, or at least not very realistic.

First of, you say you want to keep the variables and functions, and ignore function calls because of security concerns. If someone has the ability to put bad stuff in the file, then he can put it in those useful functions as well,so you wouldn't really dodge a bullet.

Secondly, you say you want to keep the variables and not run the misc. scriptcode, but i don't think that line is as clear as you perhaps imagine. Most variables in bash scripts are set using externals or by running some code or another. Lines such as DIR="$( realpath ${0} )"; are just as common as the "safe" hardcoded USERNAME="batman"; variants.

If all you need is simple hardcoded values you're likely better off just grepping for VAR=EXPR style patterns in the file and filtering that list down to useful stuff.

Anyway, thats the doom and gloom out of the way. If you're not dissuaded or if i've missed something, then there are some options i can think off that might fit you.

  1. Bash has a RESTRICTED SHELL-mode (rbash); you could check the Bash man-page for the exact details, but basically running the scripts in that may get you what you want without being exposed to many forms of security risks.

  2. You could run the script in a container (docker/podman/etc) or namespace environment (unshare and a nobody-user account).

  3. shopt exposes a extdebug option that you can enable in your bash shell or script; I haven't used it in ages, but if i remember right it basically lets you execute another shell script, and every single statement in that file is basically fed to a filter-function of yours, where you can decide if you want bash to run that line or skip it or change it or w/e.

Those are the main features that come to mind.

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.