如何将 shell 脚本的输出存储到 Unix 中的变量? [英] How to store an output of shell script to a variable in Unix?

查看:30
本文介绍了如何将 shell 脚本的输出存储到 Unix 中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 shell 脚本script.sh",当我在 unix 窗口中执行时,它会给出成功"或失败"的输出.现在我想将 script.sh 的输出存储到一个 unix 命令变量中.say $a = {output of script.sh}

i have a shell script "script.sh" which gives output as "success" or "Failed" when i execute in unix window. Now i want to store the output of script.sh into a unix command variable. say $a = {output of script.sh}

推荐答案

两个简单的例子来捕获 pwd 命令的输出:

Two simple examples to capture output the pwd command:

$ b=$(pwd)
$ echo $b
/home/user1

$ a=`pwd`
$ echo $a
/home/user1

首选第一种方式.请注意,= 之后不能有任何空格才能使其工作.

The first way is preferred. Note that there can't be any spaces after the = for this to work.

使用简短脚本的示例:

#!/bin/bash

echo "hi there"

然后:

$ ./so.sh
hi there
$ a=$(so.sh)
$ echo $a
hi there

通常,更灵活的方法是从命令返回退出值并将其用于进一步处理,尽管有时我们可能只想捕获命令的简单输出.

In general a more flexible approach would be to return an exit value from the command and use it for further processing, though sometimes we just may want to capture the simple output from a command.

这篇关于如何将 shell 脚本的输出存储到 Unix 中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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