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?

4
  • You may find envsubst helpful - see for example Replace environment variables in a file with their actual values? Nov 27, 2019 at 2:41
  • Thanks steeldriver!!! Never heard of that utilty. Got it to work using your tip:
    – user26241
    Nov 27, 2019 at 3:20
  • for i in cat mylist.txt do i=$(echo $j | envsubst) if [[ -O $i ]] && [[ -d $i ]]; then echo "found it: $i (ie, $j)" break else echo "$i is not it." fi done
    – user26241
    Nov 27, 2019 at 3:21
  • I'd actually suggest running envsubst on the whole file - see answer below Nov 27, 2019 at 3:30

2 Answers 2

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .