Many command-line programs provide switches that allow you to validate a config file before loading it. ( For example, nginx -c path/to/file -t allows users to validate a config file located at path/to/file before attempting to start nginx with that file.

Is there a similar feature for .bash_profile in bash?

  • 1
    Maybe bash -n .bash_profile? Or name it something else until you're sure it's right. – Jeff Schaller Oct 7 '16 at 18:23
  • @JeffSchaller I was thinking of maybe running it in a subshell / using the subshell as a sandbox environment. I wonder if there's a "correctly clean" way of doing that? – StudentsTea Oct 7 '16 at 18:27
  • if it was me, I'd just start with your regular bash shell, edit a file named something else (like newprofile), and run ". newprofile" until I was happy with it. – Jeff Schaller Oct 7 '16 at 18:34
  • @JeffSchaller - In this case, I'm writing a setup script that will run unattended on the machines of other developers in my dev team. It sets up global npm packages they'll need to work on the project. – StudentsTea Oct 7 '16 at 18:35
  • Are you dynamically creating the profile, then, and want to sanity-check it before pushing it out? – Jeff Schaller Oct 7 '16 at 18:42

Bash has a -n option that will

Read commands but do not execute them. This may be used to check a script for syntax errors.

It will output to stderr and set $? to 2 if there is a syntax problem. You could use it on .bash_profile like so:

bash -n .bash_profile
if [[ $? -ne 0 ]]
   # handle an error

Based on the comment string, I can't help but add a suggestion for adding these global variables in a different way. Consider a somewhat-contrived case where the user's .bash_profile had a "return" at the end of it. Appending anything (like variable assignments) would be skipped by future bash invocations. Consider putting these global variables under /etc somewhere (such as /etc/profile.d, assuming that those files get sourced by your /etc/profile); that way, you can set them based on various shell syntaxes (csh, bash), and you don't have to check to see if they're set in the user's environments OR mess with their environment files.

Another alternative would be to put these global variable assignments into a custom /etc file of your choosing, and adding in code to the .bash_profile files to source that file if it exists. This has the same disadvantage of your current plan -- editing user's local files -- but added flexibility to use different global files for different users / scenarios.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.