Shell 脚本剪切返回空字符串 [英] Shell script cut returning empty string

查看:64
本文介绍了Shell 脚本剪切返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,试图获取 linux 发行版.我有以下代码,但它返回一个空字符串.我确定我错过了什么

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 

推荐答案

正如 Honesty 的回答所说,您有两个问题.除了他的回答之外,我还想解决在您的代码中使用反引号的问题.

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.

命令替换有两种方式,一种是使用$(command),另一种是`command`.两者的工作方式相同,但 $(command) 形式是现代方式,更清晰易读.

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.

$(...) 的真正优势不在于可读性(我认为这是一个品味问题),而是嵌套命令替换的能力无需转义,并且不必担心另外必须转义 $\ 实例.- mklement0

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

以下代码使用了现代方式:

#!/bin/bash

OS=$(cat /etc/os-release | grep -sw NAME)

NEWOS=$(echo "$OS" | cut -d \" -f2)

echo $OS
echo $NEWOS

在我的电脑上输出:

NAME="Ubuntu"
Ubuntu

这篇关于Shell 脚本剪切返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆