0

Anyone who can help me fix the following ssh command to run it remotely instead of locally? It already works partly.

What I'm trying to achieve is to read all variables set in a .env file and see if a variable exists.

RELEASE_PATH=path/to/file
ssh "${USER}@${HOST}" bash -c "'
    export $(grep -E -v '^#' "${RELEASE_PATH}/.env" | xargs)

    if [ -z ${PROJECT_NAME+x} ]; then
      echo -e \"\nPROJECT_NAME=${CONTAINER_NAME}\" >> ${RELEASE_PATH}/.env
    else
      sed -i 's/PROJECT_NAME=.*/PROJECT_NAME=${CONTAINER_NAME}/g' ${RELEASE_PATH}/.env
    fi
'"

The error I'm getting at the moment is "grep: /path/to/file/.env: No such file or directory"

Twoez
  • 540
  • 1
  • 5
  • 17
  • What good does a remote `export` do at all? Its effect ends the moment the remote shell closes. – Charles Duffy Jan 04 '20 at 23:13
  • Also, if you want to export everything in a `.env` file, it's *far* less buggy to run `set -a; . "${RELEASE_PATH}/.env"; set +a`. and not use `xargs` at all. But again, that has no value/effect/point if you're running it in a remote shell that immediately exits and takes all the values you exported with it. – Charles Duffy Jan 04 '20 at 23:14
  • so -- we can make your command run remotely, but as it is, it won't accomplish anything useful. I assume you *want* it to do something useful, so... how about filling us in on what you're trying to actually accomplish? – Charles Duffy Jan 04 '20 at 23:16
  • BTW, `echo -e` should generally be avoided; the POSIX `echo` specification explicitly prohibits it, and bash can be configured at either build-time or runtime to follow that spec (in which case `echo -e foo` prints the string `-e foo` on output). Instead, use `printf '%b' 'some string with \t and \n'`, as recommended by [the POSIX spec for `echo`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html). – Charles Duffy Jan 04 '20 at 23:28
  • ...so, now that you extended your question, it's clear that there's no need to use `export` at all -- you aren't using `CONTAINER_NAME` in a subprocess that needs to be exported to, but just directly in the remote shell for generating command lines. – Charles Duffy Jan 04 '20 at 23:29
  • (`export` creates an *environment* variable, but for most purposes, regular shell variables are good enough and environment variables are unnecessary). – Charles Duffy Jan 04 '20 at 23:31
  • Hi Charles, I see a lot of things are wrong apparently ;) My main goal is to read an .env file remotely and check if a variable exists in that file or not. Thanks for the help so far. – Twoez Jan 04 '20 at 23:33
  • Yup. The linked duplicate should tell you everything you need to know; put the code to run remotely in a heredoc, passing the local variable through as shown. – Charles Duffy Jan 04 '20 at 23:34

0 Answers0