0

I have a function which should loop through every customer in an array and execute a grep to that directory.

test(){
  set -x;
  export customers=( customer1 customer2 customer3 );
  export repo_path="~/repodir";
  export output_path='/tmp';

  for i in "${customers[@]}"
  do
    echo "${repo_path}/PEC/repo-${i}/build.yml"
    grep 'link: ' $repo_path/PEC/repo-$i/build.yml | cut -d '/' -f 2 | sed 's/.git//g'
  done | sort -u > ${output_path}/repos.txt
  
  echo "${output_path}/repos.txt";
}

For some reason I get the following error message:

grep: ~/repodir/PEC/customer1/build.yml: No such file or directory

But when I check that exact same path I can see and read the file... The first echo command also doesn't seem to be executing. When I replace grep 'link: ' $repo_path/PEC/repo-$i/build.yml with grep 'link: ' ~/repodir/PEC/repo-$i/build.yml it does work.

I have tried various ways to define the variable like ${repo_path}, adding different types of quotes, ... So I basically don't know what I can do to make it work anymore.

S.J.
  • 91
  • 1
  • 10
  • 1
    Change `"~/repodir"` to `"$HOME/repodir"` the `~` does not expand within quotes. – Jetchisel Jul 12 '21 at 09:45
  • What about `$repo_path`, without the curly brackets? – Dominique Jul 12 '21 at 09:45
  • 1
    You can also move the `~` outside of quotes: `export repo_path=~/repodir` or `export repo_path=~/"repodir"`. BTW, `test` is the name of a fairly important built-in shell command, and overriding it with a function that does something else could cause really weird problems -- I'd use a different name. – Gordon Davisson Jul 12 '21 at 09:54
  • @GordonDavisson yeah I know, this was just for testing purposes :) replacing ~ works like a charm! I knew it would be something stupid... Thanks! – S.J. Jul 12 '21 at 10:05

1 Answers1

1

$HOME is an environment variable, that is set to contain the home folder of the current user. The terminal session should have access to this environment variable at all times, unless this has been removed. ~ is a shell expansion symbol, one of the symbols that is processed before the actual command is performed. ~ alone expands to the value of $HOME.

Your code, export repo_path="~/repodir";

the ~ is in a string and may not be processed, if you want to use a ~ try escaping the character. For readability using the $HOME variable would be simpler.

Shaqil Ismail
  • 1,794
  • 1
  • 4
  • 5