简体   繁体   English

将命令输出回显到终端的 shell 脚本

[英]A shell script that echo’s the commands output to the terminal

A shell script that echo's the output of the command to the terminal, so far, it's only outputting empty space.一个 shell 脚本将命令的输出回显到终端,到目前为止,它只输出空白空间。 How can I get the desired result?我怎样才能得到想要的结果? I've tried echoing the variable itself without any luck so I'm guessing the issue is with the command itself.我试过在没有任何运气的情况下回显变量本身,所以我猜问题出在命令本身上。

Actual result:实际结果:

~$ 

Preferable result:优选结果:

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"

Source code, with some comments:源代码,有一些注释:

#! /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"

As conclusion, unrelated to the logic, your script should be:作为结论,与逻辑无关,您的脚本应该是:

#!/bin/bash

function ag_students() {
    grep -i ^[a-g] /etc/passwd | cut -d: -f5
}

tmp=$(ag_students)
echo "Here are the names: $tmp"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM