user2328273
user2328273

Reputation: 968

Unexpected end of file in while loop in bash

I am trying to write a bash script that will do the following:

  1. Take a directory or file as input (will always begin with /mnt/user/)
  2. Search other mount points for same file or directory (will always begin with /mnt/diskx)
  3. Return value

So, for example, the input will be "/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.

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. 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.

Upvotes: 0

Views: 4810

Answers (1)

that other guy
that other guy

Reputation: 123410

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.
  • The shebang should be #!/usr/bin/bash or #!/bin/bash depending on your system
  • You have to assign check_var before running [ .. ] on it.
  • You have to use $(..) to expand a command
  • Variables like $i are not expanded in single quotes
  • sed can't add numbers
  • i is never incremented
  • 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.

Consider doing it in even smaller pieces, it's easier to debug e.g. the single statement sed 's:/mnt/user:/mnt/disk$i+1:' than your entire while loop.

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

Upvotes: 2

Related Questions