将命令的输出分配给变量(BASH) [英] Assigning output of a command to a variable(BASH)

查看:61
本文介绍了将命令的输出分配给变量(BASH)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将命令的输出分配给变量.我尝试的命令是:

I need to assign the output of a command to a variable. The command I tried is:

grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'

我尝试使用以下代码来分配变量:

I try this code to assign a variable:

UUID=$(grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}')

但是,它给出了语法错误.另外,我希望它可以在bash脚本中工作.

However, it gives a syntax error. In addition I want it to work in a bash script.

错误是:

./upload.sh: line 12: syntax error near unexpected token ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
 )'

./upload.sh: line 12:   ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
 )'

推荐答案

好吧,使用'$()'子shell运算符是获取bash命令输出的常用方法.由于它跨越一个子外壳,因此效率不高.

well, using the '$()' subshell operator is a common way to get the output of a bash command. As it spans a subshell it is not that efficient.

我尝试过:

UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print $1}'|awk '{print substr($0,6)}')
echo $UUID # writes e577b87e-2fec-893b-c237-6a14aeb5b390

它完美的工作:)

当然,您可以缩短命令:

Of course you can shorten your command :

# First step : Only one awk
UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print substr($1,6)}')

再一次:

# Second step : awk has a powerful regular expression engine ^^
UUID=$(cat /etc/fstab|awk '/UUID.*ext4/ {print substr($1,6)}')

您还可以将awk与文件参数:::

You can also use awk with a file argument ::

# Third step : awk use fstab directlty
UUID=$(awk '/UUID.*ext4/ {print substr($1,6)}' /etc/fstab)

这篇关于将命令的输出分配给变量(BASH)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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