How do I pass shell variables to awk command or script under UNIX like operating systems?
The -v option can be used to pass shell variables to awk command. Consider the following simple example,
root="/webroot" echo | awk -v r=$root '{ print "shell root value - " r}'
In this example search file using awk as follows:
#!/bin/bash # Usage : Search word using awk for given file. # Syntax: ./script "word-to-search" fileToSearch s=$1 i=$2 awk -v search="$s" '$0 ~ search' "$i"
Save and close the file. Run it as follows:
$ ./script.sh "vivek" /etc/passwd
Sample outputs:
vivek:x:1000:1000:Vivek Gite,,,:/home/vivek:/bin/bash
Setup shell variables using awk
You can use eval command as follows:
eval $(awk 'BEGIN{ print "vech=Bus"}' < /dev/null) echo $vech
Sample outputs:
Bus
See also:
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 4 comments… read them below or add one }
You can pass a varable directly if delimited properly. For example:
LINE="/thishost/homedir/john-doe/.sh_history" total_fields=`echo "$LINE" | awk -F/ '{print NF}'` history_file=`echo "$LINE" | awk -F/ '{print $NF}'` # Example to pass a variable in awk num_fields=`expr $total_fields - 1` user_dir=`echo $LINE |awk -F/ '{print $'''$num_fields'''}'` echo "$user_dir"Edited by Admin – added formatting to the code
This has been breaking my heart for 12 hours – thank you! I was simply trying to run commands through iteration of a char-delimited text line, so was trying to figure out how to substitute in the position parameter, via a while loop:
ix=1; while [ $ix -le `echo rpc,err,warn | awk -F, '{print NF}'` ]; do echo Huzzah `echo rpc,err,warn | awk -F”,” ‘{ print $”’$ix”’ }’`; ix=`expr $ix + 1`; done
In that case: rpc,err,warn is an example of the string I’m trying to iterate against; I’ll ultimately grep each word from a file.
Can you explain what allows the triple ”’$num_fields”’ to substitute a foreign var in for the position param?
Thanks a million!
I suggest you do this using three loops, each for rpc, err and warn
Works well once you have the format