Wednesday, March 16, 2022

[SOLVED] How can I run a command in a shell script function that requires access to the current shell instance?

Issue

I am using a custom package manager called spack, which allows me to load installed modules using the spack load command. It is similar to the familiar module load command in many ways. I am using zsh.

I have set up a shell script with a function that I would later like to insert into my .zshrc file. It is currently located in a standalone file for testing purposes, which looks as following:

#!/bin/bash
load-standard () {
    echo "loading $1"
    spack load $1
}
load-standard $1

When I run this script with source ./script_name package_name, I get an error message that says

`spack load` requires Spack's shell support.

To enable Spack's shell support, a file called setup-env.sh must be run which enables the user to make use of the spack command.

However, directly typing in the commands spack load package_name works with no problem.

I always assumed that running a command from a shell script is the same as typing it into the current shell. How can I make my shell interpret the spack load commands exactly as if I had directly typed them in?

EDIT: Placing the function in my .zshrc file solved this problem.


Solution

I'm not familiar with spack, but likely spack is a shell function which modifies the current shell environment. That is how module works. type spack to check.

You can't modify the shell environment from a script, you can from a shell function.

Copy and paste the function load-standard to "$ZDOTDIR/.zshrc" (for current user, /etc/zshrc for all users), source .zshrc (. "$ZDOTDIR/.zshrc") and you should be fine (no need to restart).

You can also create a list of functions in a file, and add . /path/to/functions to zshrc, to source it.



Answered By - dan
Answer Checked By - Terry (WPSolving Volunteer)