0

I'm trying to put together a generic script that will check the existence of several key directories for various users on different servers. Additionally, I want to leverage each user's $HOME variable.

For eg, let's say this were true:

  • on server 1: jdoe's home is /home/jdoe
  • on server 2: jdoe's home is /opt/jdoe2
  • server 3 hasn't been built yet; we won't know where they build his $HOME until the server is built.
  • on server 4: mysql's home is /opt/home/mysql

This is what I have for my important directories (ordered from most to least impt):

$ cat mylist.txt
$HOME/most_impt_dir1
$HOME/most_impt_dir2
$HOME/most_impt_dir3
$HOME/misc
$HOME/junk

...I want to find the most impt dir owned by this user.

Here's what I'm trying:

for i in `cat mylist.txt`
do

  if [[ -O $i ]] && [[ -d $i ]]; then
    echo "found it: $i"
    break
  else
    echo "$i is not it."
  fi

done

The above code does not work for anything in my list because it is literally checking for dirs beginning with $HOME. How do I get my code to use the value of the user's $HOME variable?

muru
  • 72,889

2 Answers2

1

With envsubst - replacing your for/cat loop with a while/read loop for the reasons discussed here:

#!/bin/bash

while IFS= read -r i
do

  if [[ -O $i ]] && [[ -d $i ]]; then
    echo "found it: $i"
    break
  else
    echo "$i is not it."
  fi

done < <(envsubst < mylist.txt)

See also

muru
  • 72,889
steeldriver
  • 81,074
0

Keep $HOME out of your file, and use it in your script. For example

$ cat mylist.txt
most_impt_dir1
most_impt_dir2
most_impt_dir3
misc
junk

Then:

while IFS= read -r i;
do
     dir=$HOME/$i
     if [[ -O $dir ]] ...
     ...
     fi
done < mylist.txt

Another option, given you're using bash, is to keep the list as a bash array, and source the file to get the list:

$ cat mylist.txt
dirs=(
"$HOME/most_impt_dir1"
"$HOME/most_impt_dir2"
"$HOME/most_impt_dir3"
"$HOME/misc"
"$HOME/junk"
)

Then the script will be like:

source ./mylist.txt
for dir in "${dirs[@]}"
do
    if [[ -O $dir ...
    ...
    fi
done
muru
  • 72,889