I’ve found several questions on how to pass variables from bash into awk, most notably the -v command, but I can’t quite seem to get them to do what I want.
Outside the script, the command I’m running is
awk '$2 ~ /^\/var$/ { print $1 }' /etc/fstab
Which searches /etc/fstab for JUST the /var partition, and should either print out the physical mount point, or if there isn’t one, nothing at all.
Now inside the script I have an array that contains numerous partitions, and what I want to do is iterate through that array to search fstab for each physical mount point. The problem comes in at the fact that the elements in the array have a / in them.
So what I want to do (In horrifically incorrect awk) is:
PARTITIONS=(/usr /home /var tmp);
for ((n=0; n<${#PARTITION[@]}; n++)); do
cat /etc/fstab | awk '$2 ~ /^\${PARTITIONS[$n]}$/ { print $1 }';
done
But I know that that’s not correct. The closest I have right now is:
PARTITIONS=(/usr /home /var tmp);
for ((n=0; n<${#PARTITION[@]}; n++)); do
cat /etc/fstab | awk -v partition="${PARTITIONS[$n]}" '$2 ~ /^\/var$/ { print $1," ",partition }';
done
Which at LEAST gets the partition variable into awk, but doesn’t help me at all with matching it.
So basically, I need to feed the array in, and get the physical partitions back out. Eventually the results will be assigned to another array, but once I get the output I can go from there.
I also understand awk can remove the need for the cat at the beginning, but I don’t know enough about awk to do that yet. 🙂
Thanks for any help.
EDIT
cat /etc/fstab | awk -v partition="${PARTITIONS[$n]}" '$2 ~ partition { print $1 }'
Approximates what I needed enough to be useful. I was focusing far too much on including the regex apparently. If anyone else could clean this up, it would be much appreciated 🙂
You can concatenate your regex characters (
^– beginning of string and$– end of string) and the slash which is part of the partition name and the variable containing the partition name by placing them adjacent to each other. You don’t need to use the slashes that delimit hard-coded regexes.AWK will accept the filename as an argument without using
catto pipe it or using<to redirect it.I recommend using mixed or lowercase variable names in the shell as a habit to avoid potential name collisions with shell or environment variables.