如何在 POSIX shell 中使用字符串评估变量?

chr*_*ris 0 shell ubuntu posix test docker

我有一个在 ubuntu 容器中运行的脚本:

#!/bin/sh

name=$(cat < /etc/os-release | grep "^NAME" | cut -d "=" -f 2)

if [ $name = "Ubuntu" ] 
then 
  echo "This should return"
else  
  echo "This is wrong"
fi
Run Code Online (Sandbox Code Playgroud)

我通过运行来启动容器:

docker run -it -v $(pwd):/scripts ubuntu:latest /bin/sh /scripts/test.sh
Run Code Online (Sandbox Code Playgroud)

我收到的输出是“这是错误的”,这是不对的,因为我知道 $name 的输出是“Ubuntu”,因为我的笔记本电脑是 Ubuntu,但我找不到其他原因脚本中的路由?它在容器外的笔记本电脑上做同样的事情。

And*_*ton 12

该文件/etc/os-release包含与 shell 兼容的变量赋值列表。您不需要从 shell 脚本中解析它,您只需source(或.)它并使用相关变量即可。

$ cat ex.sh
#!/bin/sh
. /etc/os-release
echo "$NAME"

$ ./ex.sh
Ubuntu
Run Code Online (Sandbox Code Playgroud)