Okay, so I am trying to use a count variable to reference the column of output sent from an echo statement. So I am trying to do this
#!/bin/bash
CURRENT=$PWD
VAR=3
CHANGE=`echo $CURRENT | awk -F "/" '{ print \$$VAR }'`
This instead of giving me the third instance after the "/" gives me the whole path. Why is this? How can I use the current method or is there a better way to parse the PWD String?
echo $CURRENT | awk -F "/" -v var=$VAR '{ print $var}'
1 Like
Thank you that did the trick!
Another way:
echo $CURRENT | awk -F "/" '{ print $'$VAR' }'
So you understand why your first attempt didn't work single quotes cause shell to not expand any variables, you needed double quotes eg:
$ VAR=7
$ echo '{ print \$$VAR }'
{ print \$$VAR }
$ echo "{ print \$$VAR }"
{ print $7 }
edit: or put the variable outside the single quotes like yinyuemi did above.
Still, escaping every character that means something to the shell is a real pain (and makes the awk script even harder to read), using -v to get variable values into awk is really the way to go.