Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1006911
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T08:32:13+00:00 2026-05-16T08:32:13+00:00

Here is a problem: In my bash scripts I want to source several file

  • 0

Here is a problem:

In my bash scripts I want to source several file with some checks, so I have:

if [ -r foo ] ; then
  source foo
else
  logger -t $0 -p crit "unable to source foo"
  exit 1
fi 

if [ -r bar ] ; then
  source bar
else
  logger -t $0 -p crit "unable to source bar"
  exit 1
fi 

# ... etc ...

Naively I tried to create a function that do:

 function safe_source() {
   if [ -r $1 ] ; then
     source $1
   else
     logger -t $0 -p crit "unable to source $1"
     exit 1
   fi 
 }

 safe_source foo
 safe_source bar
 # ... etc ...

But there is a snag there.

If one of the files foo, bar, etc. have a global such as —

declare GLOBAL_VAR=42

— it will effectively become:

function safe_source() {
  # ...
  declare GLOBAL_VAR=42
  # ...
}

thus a global variable becomes local.

The question:

An alias in bash seems too weak for this, so must I unroll the above function, and repeat myself, or is there a more elegant approach?

… and yes, I agree that Python, Perl, Ruby would make my life easier, but when working with legacy system, one doesn’t always have the privilege of choosing the best tool.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T08:32:13+00:00Added an answer on May 16, 2026 at 8:32 am

    Yes, Bash’s ‘eval’ command can make this work. ‘eval’ isn’t very elegant, and it sometimes can be difficult to understand and debug code that uses it. I usually try to avoid it, but Bash often leaves you with no other choice (like the situation that prompted your question). You’ll have to weigh the pros and cons of using ‘eval’ for yourself.

    Some background on ‘eval’

    If you’re not familiar with ‘eval’, it’s a Bash built-in command that expects you to pass it a string as its parameter. ‘eval’ dynamically interprets and executes your string as a command in its own right, in the current shell context and scope. Here’s a basic example of a common use (dynamic variable assignment):

    $>  a_var_name="color"
    $>  eval ${a_var_name}="blue"
    $>  echo -e "The color is ${color}."
    The color is blue.
    

    See the Advanced Bash Scripting Guide for more info and examples: http://tldp.org/LDP/abs/html/internal.html#EVALREF

    Solving your ‘source’ problem

    To make ‘eval’ handle your sourcing issue, you’d start by rewriting your function, ‘safe_source()’. Instead of actually executing the command, ‘safe_source()’ should just PRINT the command as a string on STDOUT:

    function safe_source() { echo eval " \
      if [ -r $1 ] ; then \
        source $1 ; \
      else \
        logger -t $0 -p crit \"unable to source $1\" ; \
        exit 1 ; \
      fi \
    "; }
    

    Also, you’ll need to change your function invocations, slightly, to actually execute the ‘eval’ command:

    `safe_source foo`
    `safe_source bar`
    

    (Those are backticks/backquotes, BTW.)

    How it works

    In short:

    • We converted the function into a command-string emitter.
    • Our new function emits an ‘eval’ command invocation string.
    • Our new backticks call the new function in a subshell context, returning the ‘eval’ command string output by the function back up to the main script.
    • The main script executes the ‘eval’ command string, captured by the backticks, in the main script context.
    • The ‘eval’ command string re-parses and executes the ‘eval’ command string in the main script context, running the whole if-then-else block, including (if the file exists) executing the ‘source’ command.

    It’s kind of complex. Like I said, ‘eval’ is not exactly elegant. In particular, there are a couple of special things you should notice about the changes we made:

    • The entire IF-THEN-ELSE block has becomes one whole double-quoted string, with backslashes at the end of each line “hiding” the newlines.
    • Some of the shell special characters like ‘”‘) have been backslash-escaped, while others (‘$’) have been left un-escaped.
    • ‘echo eval’ has been prepended to the whole command string.
    • Extra semicolons have been appended to all of the lines where a command gets executed to terminate them, a role that the (now-hidden) newlines originally performed.
    • The function invocation has been wrapped in backticks.

    Most of these changes are motived by the fact that ‘eval’ won’t handle newlines. It can only deal with multiple commands if we combine them into a single line delimited by semicolons, instead. The new function’s line breaks are purely a formatting convenience for the human eye.

    If any of this is unclear, run your script with Bash’s ‘-x’ (debug execution) flag turned on, and that should give you a better picture of exactly what’s happening. For instance, in the function context, the function actually produces the ‘eval’ command string by executing this command:

    echo eval ' if [ -r <INCL_FILE> ] ; then source <INCL_FILE> ; else logger -t <SCRIPT_NAME> -p crit "unable to source <INCL_FILE>" ; exit 1 ; fi '
    

    Then, in the main context, the main script executes this:

    eval if '[' -r <INCL_FILE> ']' ';' then source <INCL_FILE> ';' else logger -t <SCRIPT_NAME> -p crit '"unable' to source '<INCL_FILE>"' ';' exit 1 ';' fi
    

    Finally, again in the main context, the eval command executes these two commands if exists:

    '[' -r <INCL_FILE> ']'
    source <INCL_FILE>
    

    Good luck.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 499k
  • Answers 500k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This is not pretty but it works: rm -R $(ls… May 16, 2026 at 12:45 pm
  • Editorial Team
    Editorial Team added an answer Yes. Override the base1 and base2 methods in Derived to… May 16, 2026 at 12:45 pm
  • Editorial Team
    Editorial Team added an answer No, you can't. Unfortunately, UIEvent doesn't expose any public way… May 16, 2026 at 12:45 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I have added some backgrounds on stage and then on top of that adding
I have an interesting problem here... <cfloop from=1 to=#form.countField# index=i> <cfif isdefined('form[semester#i#]')> <cfquery name
I'm trying to download an html file with curl in bash. Like this site:
I'm trying to write a bash script and I needed to do some floating
I have a bash shell script that loops through all child directories (but not
I have a strange issue, relating to running a BASH script via cron (invoked
Got an annoying problem here. I've got an NHibernate/Forms application I'm working through SVN.
i'm having a small problem here. I'm using a simple rule to redirect all
I have moved my classes from a global namespace into a specific namespace. I
Cygwin user here (though if there's a suitable solution I will carry it over

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.