Bash: Pass Shell Variables To awk

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:SXI ADMIN,,,:/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:

  1. How To Use awk In Bash Scripting

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts