V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
liuguangxuan
V2EX  ›  Linux

不懂就要问, shell 脚本进入容器,执行操作后并退出的疑问。

  •  
  •   liuguangxuan · 2020-11-14 19:56:16 +08:00 · 2024 次点击
    这是一个创建于 1258 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #!/bin/bash
    docker exec -i ubuntu-lgx bash << EOF
    
    echo "test file" >> /inner.txt
    ls -l /inner.txt
    content=$(cat /inner.txt)
    echo ${conent}                                                             
    
    EOF
    

    我想在宿主机用脚本进入 docker 的容器内,然后创建了一个文件,并 cat 出来文件的内容,赋给一个变量,然后离开容器。

    但是执行的时候却提示,找不到此文件。用ls查看文件确实是存在的。

    运行结果:

    cat: /inner.txt: No such file or directory
    -rw-r--r--. 1 root root 58 Nov 14 11:51 /inner.txt
    

    请问各位老哥,这种写法哪里有什么不妥吗?

    4 条回复    2020-11-14 21:13:08 +08:00
    zhuisui
        1
    zhuisui  
       2020-11-14 20:20:04 +08:00
    是 << EOF 的部分在容器外被执行了吗
    codehz
        2
    codehz  
       2020-11-14 20:21:18 +08:00   ❤️ 1
    你没发现 cat /inner.txt 是在 host 上跑的吗
    heredoc 里$()也会被解析,
    除非你用 << 'EOF'
    xxx
    EOF
    这样的格式
    adminpassword
        3
    adminpassword  
       2020-11-14 20:53:57 +08:00
    可以在宿主机上创建好文件,然后 docker cp 到容器里
    liuguangxuan
        4
    liuguangxuan  
    OP
       2020-11-14 21:13:08 +08:00
    @zhuisui #1
    @codehz #2
    @adminpassword #3
    明白原因了,是因为 EOF 没有加单引号,学习到了新知识,heredoc 。感谢各位老哥。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   982 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 21:30 · PVG 05:30 · LAX 14:30 · JFK 17:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.