pythonbashconda

Syntax error near token on bash script initialising conda


I've been asked to add some BASH script to a server .bashrc file so I can then initialise conda.

When I log into the server, I get the following message:

Last login: Wed Aug 28 16:57:04 2024 from {IP ADDRESS}

-bash: /home/{username}/.bashrc: line 129: syntax error near unexpected token `then' 

-bash: /home/{username}/.bashrc: line 129: `    if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then' 

Here's the code:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/opt/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

I ran the bash script through shellcheck and it produced this:

Line 126: if [ $? -eq 0 ]; then ^-- SC1046 (error): Couldn't find 'fi' for this 'if'. ^-- SC1073 (error): Couldn't parse this if expression. Fix to allow more checks. 
Line 129:     if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then ^-- SC1047 (error): Expected 'fi' matching previously mentioned 'if'. >> ^-- SC1072 (error): Unexpected keyword/token. 
Fix any mentioned problems and try again

Can anybody see the error?

Edit: The /opt/anaconda3/bin/conda file is definitely there, and the /opt/anaconda3/etc/profile.d/conda.sh file is also there.


Solution

  • Your file is filled with non-ASCII characters. For example, here's a hexdump of line 7:

    $ sed -n 7p foo.sh  | xxd
    00000000: e280 afe2 80af e280 af20 6966 205b 202d  ......... if [ -
    00000010: 6620 222f 6f70 742f 616e 6163 6f6e 6461  f "/opt/anaconda
    00000020: 332f 6574 632f 7072 6f66 696c 652e 642f  3/etc/profile.d/
    00000030: 636f 6e64 612e 7368 2220 5d3b 2074 6865  conda.sh" ]; the
    00000040: 6e0a                                     n.
    

    The byte sequence e280f is a NARROW NO-BREAK SPACE, and bash doesn't know what to do with that. Replace all the whitespace with actual spaces; the code is otherwise correct.

    # >>> conda initialize >>>
    # !! Contents within this block are managed by 'conda init' !!
    __conda_setup="$('/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2>/dev/null)"
    if [ $? -eq 0 ]; then
      "$__conda_setup"
    else
      if [ -f "/opt/anaconda3/etc/profile.d/conda.sh" ]; then
        . "/opt/anaconda3/etc/profile.d/conda.sh"
      else
        export PATH="/opt/anaconda3/bin:$PATH"
      fi
    fi
    unset __conda_setup
    # <<< conda initialize <<<