Question: Lists are commonly stored in environment variables by putting a colon (:) between each of the list elements. (The value of the PATH variable is

Lists are commonly stored in environment variables by putting a colon (:) between each of the list elements. (The value of the PATH variable is an example.) You can add an element to such a list by catenating the new element to the front of the list, as in

PATH=/opt/bin:$PATH

If the element you add is already in the list, you now have two cop:wqies of it in the list.


Write a shell function named addenv that takes two arguments: (1) the name of a shell variable and (2) a string to prepend to the list that is the value of the shell variable only if that string is not already an element of the list. For example, the call

addenv PATH /opt/bin

would add /opt/bin to PATH only if that pathname is not already in PATH. Be sure your solution works even if the shell variable starts out empty. Also make sure you check the list elements carefully. If /usr/opt/bin is in PATH but /opt/bin is not, the example just given should still add /opt/bin to PATH. (Hint:You might find this exercise easier to complete if you first write a function locate_field that tells you whether a string is an element in the value of a variable.)

Script: #/bin/bash # locate field function function locate field0 # parameters passed to the function env_var $(eval echo $$1) field-$2 # flag variable found found-0 # case when given environment variable value is empty list-len-${#env-var) if [ $list_len -eq 0] then return 2 old_val-lFS IFS- for each_path in $env_var if [ $each_path then found-1 $field] done IFS-$old val return $found

Script: #!/bin/bash # locate field function function locate_field(){ # parameters passed to

Script: #!/bin/bash # locate field function function locate_field(){ # parameters passed to the function env_var=$(eval echo '$'$1) field=$2 # flag variable found found=0 # case when given environment variable value is empty list_len=${#env_var} if [ "$list_len" -eq 0] then return 2 fi old_val=IFS IFS=: for each_path in $env_var do if [ "$each_path" : "$field" ] == then found=1 fi done IFS=$old_val return $found }

Step by Step Solution

3.51 Rating (154 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Copy the script and run Look for indentation and instructio... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Finance Questions!