简体   繁体   中英

Reading lines in a text file by Bash Script

I'm going to read lines in a text file:

$SSH_PRIVATE_FILE="address"

I would like to read and evaluate the line in a way to assign a value to the already defined SSH_PRIVATE_FILE .

The follwing is a docker file's contents

ARG SSH_PRIVATE_FILE
COPY build-params build-params
RUN while IFS='' read -r line || [ -n "$line" ]; do\
    echo "Text read from file: $line";\
    eval `$line`;\
    done < "build-params"

RUN echo $SSH_PRIVATE_FILE

UPDATED

But it returns error: /bin/sh: 1: $SSH_PRIVATE_FILE="~/.ssh/id_rsa": not found

Bourne-type shells have a built-in mechanism to read the contents of a text file and evaluate each line, the . directive. (GNU bash has the same functionality under the name source , but this is not part of the POSIX shell standard and some very-light-weight shells in Docker base images don't support it.) At a shell level, what you've written is equivalent to

. ./build-params

However, each Dockerfile RUN line runs a separate container with a separate shell with a clean shell environment, so this turns out to be a pretty bad way to set environment variables. The Dockerfile ENV directive works better.

Furthermore, since you're writing the Dockerfile, you have complete control over the filesystem layout inside the Dockerfile, and you don't really need the locations of things inside the Docker container to be parametrizable. In the case of things like credentials, you'd use the docker run -v option to inject things into the container. If I needed a setting like this, I might make my Dockerfile say

ENV SSH_PRIVATE_FILE=/ssh/id_rsa

and then actually launch the container as

docker run -v $HOME/.ssh:/ssh ...

and not make this a build-time option at all.

只是一个疯狂的猜测,但我会尝试在每行的每个\\之前放置一个空格。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM