Shell – How to evaluate a variable with a string in the POSIX shell

dockerposixshelltestUbuntu

I have a script that I am running inside a ubuntu container:

#!/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

I started the container by running:

docker run -it -v $(pwd):/scripts ubuntu:latest /bin/sh /scripts/test.sh

The output I am receiving is "This is wrong" which is not right because I know that the output of $name is "Ubuntu" because my laptop is Ubuntu but I can't find a reason as to why this is going down the else route in the script? It does the same thing on my laptop outside the container.

Best Answer

The file /etc/os-release contains a list shell-compatible variable assignments. You don't need to parse it from a shell script, you can just source (or .) it and use the relevant variables.

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

$ ./ex.sh
Ubuntu
Related Question