[英]Unexpected end of file in while loop in bash
I am trying to write a bash script that will do the following: 我正在尝试编写将执行以下操作的bash脚本:
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: 这里有很多问题:
#!/usr/bin/bash
or #!/bin/bash
depending on your system shebang应该是#!/usr/bin/bash
或#!/bin/bash
具体取决于您的系统 check_var
before running [ .. ]
on it. 您必须在check_var
运行[ .. ]
之前分配check_var
。 $(..)
to expand a command 您必须使用$(..)
展开命令 $i
are not expanded in single quotes 像$i
这样的变量不会用单引号引起来 sed
can't add numbers sed
无法添加数字 i
is never incremented i
永远不会增加 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.