linux - 将命令输出到终端的 shell 脚本
问题描述
一个将命令输出回显到终端的 shell 脚本,到目前为止,它只输出空白空间。我怎样才能得到想要的结果?我试过在没有任何运气的情况下回显变量本身,所以我猜问题出在命令本身。
实际结果:
~$
优选结果:
Name N. Name
Name N. Name
Name N. Name
Name N. Name
#! /bin/bash
function ag_students() {
ag_names=$(grep -i ^[A-G] /etc/passwd | cut -d: -f5 /etc/passwd > tmp | echo "$tmp" ;)
echo "$tmp"
}
$ag_students
echo "Here are the names: $tmp"
解决方案
源代码,带有一些注释:
#! /bin/bash
function ag_students() {
# grep -i ^[A-G] -> grep -i [a-g] # it is absolutely same but you do not need to hit your [shift] key repeatedly.
# <command> | cut -d: -f5 /etc/passwd
# It is stange for me. From the one point of view you want to handle the output
# of the <command1> using <command2> ("cut" utility).
# From the other side you specified the input file for it (/etc/passwd)
# Look at the "cut --help"
# Thus it should be:
# grep -i ^[a-g] /etc/passwd | cut -d: -f5
# without any additions
# Next: "<command> > <name>" will store its output to the file <name>, not to the variable <name>
# "cut -d: -f5 /etc/passwd > tmp" will store its output to the file "tmp", not to the variable with same name
# finally, because, according above, variable "$tmp" still not initialized,
# "echo "$tmp"" will return the empty string whith is assigned to "ag_names" variable
# ag_names=$(grep -i ^[A-G] /etc/passwd | cut -d: -f5 /etc/passwd > tmp | echo "$tmp" ;)
# The right solution:
ag_names=$(grep -i [a-g] /etc/passwd | cut -d: -f5)
# or simpy
grep -i [a-g] /etc/passwd | cut -d: -f5
# It is unnecessary because previous bunch of command alredy output what you want
# echo "$tmp"
}
# Using dollar sign you are trying to execute command contains in the "ag_students" variable (which is not initialized/empty)
# and executing something empty you will get empty result also
$ag_students
# to execute a function - execute it as any other command:
ag_students
# And if you want to have its result in some variable:
tmp=$(ag_students) # as usual
echo "Here are the names: $tmp"
作为结论,与逻辑无关,您的脚本应该是:
#!/bin/bash
function ag_students() {
grep -i ^[a-g] /etc/passwd | cut -d: -f5
}
tmp=$(ag_students)
echo "Here are the names: $tmp"
推荐阅读
- android - 对 web 和 android 应用程序呈现不同的响应
- angular - 升级 ag-grid 角度版本
- bash - 防止使用 GitHub 时将大文本文件添加到提交
- c++ - 可以像在其他编译器中的 Microsoft C 中那样使用类型化或类型名声明构造函数吗?
- java - Android Intent 地图数据被覆盖
- airflow - Apache - Airflow 1.10.1 不开始工作
- java - Pyspark:python 工作者无法连接回来/socketTimeOut
- reactjs - 我可以在组件中访问的道具无法呈现
- php - PHP - 如何在导入期间在自定义字段中设置日期和时间戳
- ios - 将 UIViewController 呈现为弹出框