Bash – How to Use the $HOME Variable in Scripts

bashscriptingshell-script

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?

Best Answer

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

Related Question