首页 > 解决方案 > 将命令输出到终端的 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"

标签: linuxbashubuntuunix

解决方案


源代码,带有一些注释:

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

推荐阅读