繁体   English   中英

Shell 逐行读取文件,但在每一行之后都显示未找到。 我错过了什么?

[英]Shell reads the file line by line, but after each line it says not found. What am i missing?

我正在尝试创建一个 shell 脚本来创建用户并从 ubuntu 18.04 中的 txt 文件中的列表中创建/添加每个组。 我在读取输入文件时遇到问题。

抱歉,我是脚本初学者,但我有其他语言的经验。

我尝试在 while 和 for 循环之间切换(没关系)并且我已经修复了路径以便它可以读取文件,但是在每一行之后它都会显示“bob:未找到”。 现在,当我尝试修复它时,我只是让它回响。

到目前为止,这是我的 shell 脚本:GNU nano 2.5.3 文件:shell_lab

#!/bin/sh
# test
cd "$(dirname "$0")"

echo "script running"

for line in $(./input.txt)
do
        echo "$line"
done

这是我的输入文件(在同一目录中):

GNU nano 2.5.3 文件:input.txt

bob
larry
joe

我希望得到回应:bob larry joe

这就是我得到的:konather@ubuntu:~$ sudo./shell_lab

script running
./input.txt: 1: ./input.txt: bob: not found
./input.txt: 2: ./input.txt: larry: not found
./input.txt: 3: ./input.txt: joe: not found`

我也试过这个我发现的结果相同:

#!/bin/sh

for i in `./input.txt`
do
echo $i
# echo $i"123" | passwd "$i" --stdin
# echo; echo "User $username's password changed!"
done

上面已经解决了,下面还有一个问题

我还有一个稍微无关的问题。 我现在正在尝试自动创建密码。 我已经从 pipe 中的 input.txt 文件中回显密码,但我认为它实际上并没有响应我的提示。

while read u1 p1 do echo "$p1" |echo "$p1"| passwd $u1 # echo "$u1 had the password changed to $p1" done < input.txt while read u1 p1 do echo "$p1" |echo "$p1"| passwd $u1 # echo "$u1 had the password changed to $p1" done < input.txt结果: script running Enter new UNIX password: Retype new UNIX password: passwd: Authentication token manipulation error passwd: password unchanged

$(./input.txt)是尝试调用命令./input.txt的命令替换 根据您的描述input.txt不是生成列表的可执行文件,而是包含以下内容的文本文件:

$ cat input.txt
bob
larry
joe

如果要遍历文件中的行,则需要将文件重定向为输入。 您可以通过在命令替换中包含重定向运算符来做到这一点,例如$(<./input.txt) ,但如评论中所述,您最好将文件重定向到while循环,例如

#!/bin/sh
# test
cd "$(dirname "$0")"

echo "script running"

while read line
do
    echo "$line"
done < input.txt

示例使用/输出

$ sh test.sh
script running
bob
larry
joe

您应该通过检查line是否由read初始化来防止没有 POSIX 文件结尾的文件(例如,在最后一行之后没有'\n' ),例如

while read line || [ -n "$line" ]
do
    echo "$line"
done < input.txt

这将允许您阅读和 output 最后一行,无论输入文件中的最后一行文本之后是否有适当的行结束。

如果您还有其他问题,请仔细查看并告诉我。

暂无
暂无

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

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