0

I want to run this code:

#! /bin/sh

env_name="base"
source activate $env_name

in my shell as sh filename.sh, but an error say:

filename.sh: source: not found

with the following line:

filename.sh: Syntax error: Unterminated quoted string

what is the problem? It is good to say that I can run this command in shell manually but when I try to run as shell script this problem gives me the error. any help appreciated.

Hosein Basafa
  • 1,068
  • 8
  • 11

2 Answers2

0

Options

You have three options:

  1. Login Mode - use a shell in login mode that automatically sets up Conda's shell functionality.
  2. Manual initialization - where you manually source the shell-appropriate initialization script to enable conda activate functionality in your script.
  3. conda run - where you let Conda auto-activate the env for you.

1: Login Mode

Typical Conda installations have users run conda init for their primary shell, which adds code to the user's shell-specific resource file (e.g., .bashrc). The current way OP runs the script, and the script's shebang, will never load such a resource and therefore do not define the conda activate function.

Instead, redefine the shebang to use a full shell and run in login mode. For example, this would be the BASH version:

#!/usr/bin/env bash -l

and run with either

. filename.sh

or

bash -l filename.sh

This assumes the user has run conda init bash.


2: Manual Initialization

The conda activate functionality is normally a shell function that Conda creates at the start up of your interactive shells. To use this same functionality in scripts, you can manually run the initialization script. Assuming a bash type shell, this is located under the base Anaconda/Miniconda directory at etc/profile.d/conda.sh. Let's assume you have it at:

/Users/user/miniconda3/etc/profile.d/conda.sh

A working version of your script would then go something like

#!/bin/sh

. /Users/user/miniconda3/etc/profile.d/conda.sh
conda activate base

...

3: Conda Run

You can use conda run (see conda run --help) in the shebang to automatically activate the env and run everything in the script in that context. This assumes that you have properly configured your shell to use conda. For example,

#!/usr/bin/env conda run -n base bash

some_cmd

where some_cmd is a commandline program that is available in your env.

merv
  • 67,214
  • 13
  • 180
  • 245
0

There is no command named source in POSIX shell. To source a file, use a period, i.e.

. filename.sh
user1934428
  • 19,864
  • 7
  • 42
  • 87