0

I'm trying to create a script that creates scripts (and do other things). My problem is that these scripts created contain environment variables, and when actually running my script, they do not appear in the script.

#!/bin/bash
for i in {001..116}
do
   rm job
   cat > job <<!
#PBS -S /bin/bash
#PBS -N $i-Fe63S
#PBS -j oe
#PBS -q default
#PBS -l nodes=1:ppn=24
#PBS -l walltime=48:00:00
#PBS -V
cd $PBS_O_WORKDIR  
/opt/openmpi/bin/mpirun -np 24 /opt/vasp/5.4/vasp.5.4.1/bin/vasp_std > log
!
   mkdir $i
   cp job $i/
done

In the resulting "job" file created, it attempts, but fails to find the $PBS_O_WORKDIR, so the resulting script is

#PBS -S /bin/bash
#PBS -N 116-Fe63S
#PBS -j oe
#PBS -q default
#PBS -l nodes=1:ppn=24
#PBS -l walltime=48:00:00
#PBS -V

cd

/opt/openmpi/bin/mpirun -np 24 /opt/vasp/5.4/vasp.5.4.1/bin/vasp_std > log

How do i modify the script, so the line in the result script is written "cd $PBS_O_WORKDIR" rather than "cd"?

Jota Be
  • 3
  • 1
  • @KevinMGranger, I disagree that that's a good duplicate. The question is not about how to write the heredoc to a file, but how to suppress variable expansions in the process. – Charles Duffy Aug 04 '17 at 20:06
  • The first, accepted answer of @KevinMGranger’s suggestion has a section about here documents where variables do not get interpreted. – Daniel H Aug 04 '17 at 20:27
  • @JotaBe, ...by the way -- be sure to quote your expansions. `mkdir $i` is *not* the same as `mkdir "$i"` -- even if you know that `i` is always numeric, if `IFS=0` and `i=102` then `mkdir $i` will create two directories named `1` and `2`, not one directory named `102`. – Charles Duffy Aug 04 '17 at 20:31
  • Deleted my dupe comment as Benjamin's suggestion is better. – Kevin M Granger Aug 04 '17 at 21:16

2 Answers2

1

Go through the variables/expressions in your here document and escape the ones you don't want expanded at the point when you write the file.

In this case you want $i expanded now, and $PBS_O_WORKDIR expanded later, so you escape the latter:

#!/bin/bash
for i in {001..116}
do
   rm job
   cat > job <<!
#PBS -S /bin/bash
#PBS -N $i-Fe63S
#PBS -j oe
#PBS -q default
#PBS -l nodes=1:ppn=24
#PBS -l walltime=48:00:00
#PBS -V
cd \$PBS_O_WORKDIR    # <- Escaped
/opt/openmpi/bin/mpirun -np 24 /opt/vasp/5.4/vasp.5.4.1/bin/vasp_std > log
!
   mkdir $i
   cp job $i/
done
that other guy
  • 116,971
  • 11
  • 170
  • 194
0

Quote your heredoc sigil to prevent expansions from taking place inside the contents:

cat >job <<'!'

...or...

cat >job <<\!

...not...

cat >job <<!
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • This is very helpful! I didn't know you could prevent expansions inside the whole cat like that. But in this case i need one variable expanded "$i" and the other one not. – Jota Be Aug 04 '17 at 20:29