Shell script cut returning empty string

2019-03-03 08:38发布

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 

标签: sh
3条回答
我想做一个坏孩纸
2楼-- · 2019-03-03 09:23

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.

查看更多
我命由我不由天
3楼-- · 2019-03-03 09:27

You have two problems.

  1. Typing just $OS doesn't output anything to stdout (which is piped to cut).

  2. 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)

查看更多
该账号已被封号
4楼-- · 2019-03-03 09:36

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
查看更多
登录 后发表回答