简体   繁体   English

bash中while循环中文件意外结束

[英]Unexpected end of file in while loop in bash

I am trying to write a bash script that will do the following: 我正在尝试编写将执行以下操作的bash脚本:

  1. Take a directory or file as input (will always begin with /mnt/user/) 将目录或文件作为输入(将始终以/ mnt / user /开头)
  2. Search other mount points for same file or directory (will always begin with /mnt/diskx) 在其他安装点中搜索相同的文件或目录(将始终以/ mnt / diskx开头)
  3. Return value 返回值

So, for example, the input will be "/mnt/user/my_files/file.txt". 因此,例如,输入将为“ /mnt/user/my_files/file.txt”。 It will search if ""/mnt/disk1/my_files/file.txt" exists and will incrementally look for each disk (disk2, disk3, etc) until it finds it or disk20. 它将搜索是否存在“” /mnt/disk1/my_files/file.txt”,并将逐步查找每个磁盘(disk2,disk3等),直到找到它或disk20。

This is what I have so far: 这是我到目前为止的内容:

#/user/bin/bash
var=$1
i=0
while [ -e $check_var = echo $var | sed 's:/mnt/user:/mnt/disk$i+1:']
do
final=$check_var
done

It's incomplete yes, but I am not that proficient in bash so I'm doing a little at a time. 是的,这是不完全的,但是我对bash的了解并不那么精通,所以我一次只做些事情。 I'm sure my command won't work properly yet either but right now I am getting an "unexpected end of file" and I can't figure out why. 我确定我的命令也无法正常工作,但是现在我遇到了“意外的文件结尾”,我不知道为什么。

There are many issues here: 这里有很多问题:

  • If this is the actual code you're getting "unexpected end of file" on, you should save the file in Unix format, not DOS format. 如果这是要获取“文件末尾”的实际代码,则应将文件保存为Unix格式,而不是DOS格式。
  • The shebang should be #!/usr/bin/bash or #!/bin/bash depending on your system shebang应该是#!/usr/bin/bash#!/bin/bash具体取决于您的系统
  • You have to assign check_var before running [ .. ] on it. 您必须在check_var运行[ .. ]之前分配check_var
  • You have to use $(..) to expand a command 您必须使用$(..)展开命令
  • Variables like $i are not expanded in single quotes $i这样的变量不会用单引号引起来
  • sed can't add numbers sed无法添加数字
  • i is never incremented i永远不会增加
  • the loop logic is inverted, it should loop until it matches and not while it matches. 循环逻辑是相反的,它应该循环直到匹配为止,而不是匹配为止。
  • You'd want to assign final after -- not in -- the loop. 您想在循环之后而不是循环中分配final

Consider doing it in even smaller pieces, it's easier to debug eg the single statement sed 's:/mnt/user:/mnt/disk$i+1:' than your entire while loop. 考虑将其分成更小的部分,它比例如整个while循环更容易调试,例如单个语句sed 's:/mnt/user:/mnt/disk$i+1:'

Here's a more canonical way of doing it: 这是一种更规范的方法:

#!/bin/bash
var="${1#/mnt/user/}"
for file in /mnt/disk{1..20}/"$var"
do
  [[ -e "$file" ]] && final="$file" && break
done

if [[ $final ]]
then
  echo "It exists at $final"
else
  echo "It doesn't exist anywhere"
fi

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

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