0

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.

2
  • 1
    You're not taking into account the literal quotes around the string "Ubuntu" Commented Jul 4, 2020 at 0:16
  • 6
    Welcome! As a first step, please have a look at what shellcheck.net says about your script. Commented Jul 4, 2020 at 0:24

4 Answers 4

12

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
3

On Debian, that particular line is

NAME="Debian GNU/Linux"

Note the quotes on the right hand side. If they are there on Ubuntu too, then you'll get literal quotes in name, too, since quotes aren't special to cut. Another issue is that the string may contain whitespace, in which case word splitting hits on the unquoted variable expansion in [ $name = "Ubuntu" ], and the test will likely give an error.

To avoid those issues, quote the variable expansion, and add the literal quotes on the comparison string:

if [ "$name" = '"Ubuntu"' ]; then ...

Or remove the quotes from the start and end of the string: name=${name#\"}; name=${name%\"}, and still quote "$name".

0
1

In this particular case, you could simplify your script as in:

#!/bin/sh

if grep -q Ubuntu /etc/os-release; then
  echo "This should return"
else
  echo "This is wrong"
fi

grep, when passed the -q option, will not print anything but exit with a code of 0 when the string is found, non-zero otherwise. That is what if expects, after all.

0

Minimalistic

$ grep -q Ubuntu /etc/os-release && echo "This should return" || echo "This is wrong"

or

$ . /etc/os-release && echo "$NAME"

or you can use lsb_release command also

$ lsb_release -i -s
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.