I am writing a script that I am trying to get the linux distribution. I have the following code but it is returning an empty string. I am sure I am missing something
OS=`cat /etc/os-release | grep -sw NAME`
NEWOS=$OS | `cut -d \" -f2`
echo $NEWOS
I am writing a script that I am trying to get the linux distribution. I have the following code but it is returning an empty string. I am sure I am missing something
OS=`cat /etc/os-release | grep -sw NAME`
NEWOS=$OS | `cut -d \" -f2`
echo $NEWOS
Like Honesty's answer says, you have two problems. Adding to his answer, I'd also like to address the use of backticks in your code.
The command substitution can be done in two ways one is using $(command)
and the other is `command`
. Both work the same, but the $(command)
form is the modern way and has more clarity and readability.
The real advantage of
$(...)
is not readability (that's a matter of taste, I'd say), but the ability to nest command substitutions without escaping, and to not have to worry about additionally having to escape$
and\
instances. - mklement0
The following code uses the modern way:
#!/bin/bash
OS=$(cat /etc/os-release | grep -sw NAME)
NEWOS=$(echo "$OS" | cut -d \" -f2)
echo $OS
echo $NEWOS
Output on my computer:
NAME="Ubuntu"
Ubuntu
You have two problems.
Typing just $OS
doesn't output anything to stdout (which is piped to cut
).
Your second problem is that you put cut
in backticks. This means that you're trying to run the output of an empty cut.
The solution is to write $(echo "$OS" | cut -d \" -f2)
To complement the existing, helpful answers with an alternative way to solve the problem, using a single awk
command:
os=$(awk -F\" '/^NAME=/ { print $2 }' /etc/os-release)
echo "$os"
Note that I've changed the case of the variable from OS
to os
, because it's better not to use all-uppercase shell-variable names in order to avoid conflicts with environment variables and special shell variables.