Shell script cut returning empty string

喜欢而已 提交于 2019-12-02 08:09:13

问题


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 

回答1:


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



回答2:


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)




回答3:


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.



来源:https://stackoverflow.com/questions/36732828/shell-script-cut-returning-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!