Linux系统
Linux物理层
LSI Raid 阵列日常操作
MegaCLI基本使用指南
重要参数含义说明
Linux系统层
timedatectl命令时间时区操作
sar命令用法
Linux 性能调优工具9张图
Linux 特殊权限说明
Linux系统三级等保整改脚本
CentOS7 多网卡单网关利用策略路由实现源进源出
初始化Linux数据盘(parted)
解决CentOS7下yum命令的异常
Linux 修改系统语言环境
中标麒麟安装Nvidia显卡驱动
Linux主机双网卡同网段同网关配置
Linux查看主板内存槽与内存信息
安装麒麟Kylin-v10 Arm64版本到阿里云
EXSI虚机mount出现‘unknown filesystem type 'LVM2_member'’
Linux 服务层
Linux主机挂载共享samba出现普通用户没有写权限的问题
CentOS 7.x通过rpm升级OpenSSH到 8.5p1版本
编译OpenSSH的rpm包并升级
linux命令集
磁盘工具集
Linux du 命令
字符处理集
Linux sed 命令
Linux命令输出重定向到变量
网络工具集
MTR探测主机间丢包
常用调试指令集
Linux性能测试
甲骨文主机测试
本文档使用 MrDoc 发布
-
+
home page
Linux命令输出重定向到变量
## 前言 在Linux中,有部分命令的输出会直接打印到控制台,无法通过直接赋值的方式实现将输出内容赋值给变量. ------------ ## 示例 **Example**: - 示例可正常赋值的结果 ```bash [root@localhost ~]# cat /etc/passwd|head -1 root:x:0:0:root:/root:/bin/bash [root@localhost ~]# [root@localhost ~]# a1=$(cat /etc/passwd|head -1) [root@localhost ~]# [root@localhost ~]# echo $a1 root:x:0:0:root:/root:/bin/bash ``` - 示例不可正常赋值的结果 ```bash [root@localhost ~]# [root@localhost ~]# /data/nginx/sbin/nginx -t nginx: the configuration file /data/nginx/conf/nginx.conf syntax is ok nginx: configuration file /data/nginx/conf/nginx.conf test is successful [root@localhost ~]# [root@localhost ~]# a2=$(/data/nginx/sbin/nginx -t) nginx: the configuration file /data/nginx/conf/nginx.conf syntax is ok nginx: configuration file /data/nginx/conf/nginx.conf test is successful [root@localhost ~]# [root@localhost ~]# echo $a2 [root@localhost ~]# ``` 如上所示,当命令结果赋值给变量时,控制台仍会输出标准输出内容,并且无法正常将输出结果赋值给变量。 ## 方法 使用重定向指令解决该问题,将指定的输出通过`标准输出(stdout)`和`错误输出(stderr)`进行输出重定向,并对其赋值即可 - 示例将不可正常赋值的输出进行重定向输出并赋值 ```bash [root@localhost ~]# /data/nginx/sbin/nginx -t nginx: the configuration file /data/nginx/conf/nginx.conf syntax is ok nginx: configuration file /data/nginx/conf/nginx.conf test is successful [root@localhost ~]# [root@localhost ~]# a2=$(/data/nginx/sbin/nginx -t 2>&1) [root@localhost ~]# [root@localhost ~]# echo $a2 nginx: the configuration file /data/nginx/conf/nginx.conf syntax is ok nginx: configuration file /data/nginx/conf/nginx.conf test is successful [root@localhost ~]# ```
Nathan
Oct. 19, 2022, 2:44 p.m.
转发文档
Collection documents
Last
Next
手机扫码
Copy link
手机扫一扫转发分享
Copy link
本站将从https://wiki.netimed.cn
转移到
https://www.netimed.cn
,悉知!
联系邮箱:service@netimed.cn
Markdown文件
PDF文件
Docx文件
share
link
type
password
Update password