[BASH] eval command not expanding variables as expected.


Login or Register for Dates, Times and to Reply

 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers [BASH] eval command not expanding variables as expected.
# 1  
[BASH] eval command not expanding variables as expected.

Hi Guys,


I wrote a collection of bash functions years ago and now need to use them again but
I'm getting some error messages when eval tries to expand the variables names.


I recollect that I used the shopt command to set one of the options but I can't quite
remember the command that I used. However, I may be wrong regarding the shopt
command.


Anyway, the function in question is:
Code:
function array_load
 {
    local IFS=$'\n'
    eval "$1=( \$( < \"\${$2}\" ) )"
 }

This is the output from the sh -x command:
Code:
+ declare -i __ITR__
+ declare -a __FILE_SQL__
+ declare -a __TEMP_SQL__
+ array_load __FILE_SQL__ __SRC__
+ local 'IFS=
'
+ eval '__FILE_SQL__=( $( < "${__SRC__}" ) )'
++ __FILE_SQL__=($( < "${__SRC__}" ))
  /Users/Shared/#BASHLIB/type/array.bash: line 53: ~/djia.csv: No such file or directory

The __SRC__ variable contains a relative reference to a file i.e. ~/djia.csv but I've also
tried using an absolute reference from the root directory which also does not get found.


Any help would be appreciated.
TIA Guys. ;-)
# 2  
I'd trust the system when it complains a file not residing where it looks for it.
Did you make very sure that file exists?


What happens in your script is that bash's mapfile / readarray builtin is duplicated by using a "command substitution". man bash:
Quote:
The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).
Above mentioned builtins serve the same purpose, offer some more options, and don't rely on the deprecated, dangerous eval command. man bash:
Quote:
mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
Read lines from the standard input into the indexed array variable array
Why don't you just abandon the function?

Last edited by RudiC; 3 Weeks Ago at 04:30 PM..
# 3  
you can also read from a file into an associative array
Code:
cat file
(
[apple]=123457
[mango]=123456
[orange]=1234567
)
declare -A arr
m=arr
eval $m=$(<file)
echo ${arr[@]}
1234567 123456 123457
echo ${!arr[@]}
orange mango apple

# 4  
probably
Code:
shopt -s extquote

# 5  
Hi nezabudka...
Quote:
you can also read from a file into an associative array
Remember! Only on bash version 4.0.x and above.
We Apple users and probably others only have version 3.2.x so associative arrays are a none starter.
As the OP has not quoted his bash version nor the OS and HW in use then we can only assume he MIGHT have bash version 4.0.x[plus] available.

Just an observation...
This User Gave Thanks to wisecracker For This Post:
# 6  
Hi.
Quote:
Originally Posted by wisecracker
Hi nezabudka...
Remember! Only on bash version 4.0.x and above.
We Apple users and probably others only have version 3.2.x so associative arrays are a none starter.
As the OP has not quoted his bash version nor the OS and HW in use then we can only assume he MIGHT have bash version 4.0.x[plus] available.

Just an observation...
I think those of us who use macos may need to get used to zsh. Here is a demo zsh script that was run on Mojave, not using eval:
Code:
#!/usr/bin/env zsh

# @(#) z1       Demonstrate feature.

set +o nounset
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && zsh $C
set -o nounset

FILE=${1-data1}

pl " Input file $FILE:"
head $FILE

# IFS=$'\n,'; h=($(<file.csv))
# https://unix.stackexchange.com/questions/464626/making-associative-array-based-on-another-associative-array
# Printing advice from:
# http://zsh.sourceforge.net/Guide/zshguide05.html#l122
pl " Results:"
typeset -A a
IFS=$'\n,\t='; a=($(<$FILE))

pe;pe " Plain print:"
print ${a}
pe;pe " Values:"
print ${(v)a}
pe;pe " Keys:"
print ${(k)a}
pe;pe " Both vertically:"
print -l "${(@kv)a}"

exit 0

producing:
Code:
$ ./z1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Apple/BSD, Darwin 18.7.0, x86_64
Distribution        : macOS 10.14.6 (18G103), Mojave
zsh 5.3

-----
 Input file data1:
red=stop
green=go
yellow=caution

-----
 Results:

 Plain print:
caution stop go

 Values:
caution stop go

 Keys:
yellow red green

 Both vertically:
yellow
caution
red
stop
green
go

Best wishes ... cheers, drl
These 2 Users Gave Thanks to drl For This Post:
# 7  
Quote:
Originally Posted by ASGR
Hi Guys,


I wrote a collection of bash functions years ago and now need to use them again but
I'm getting some error messages when eval tries to expand the variables names.
The problem is ~ is not being expanded. It turns out to be a little tricky to expand ~ but also avoid word separation on the path name (white spaces in you array source filename).

Try:
Code:
function array_load
{
    local IFS=$'\n'
    local ARR_FILE=$(eval echo ${!2})
    eval "$1=( \$( < \"$ARR_FILE\" ) )"
}

These 2 Users Gave Thanks to Chubler_XL For This Post:
Login or Register for Dates, Times and to Reply

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Test Your Knowledge in Computers #827
Difficulty: Medium
Douglas Crockwell first specified and popularized the JSON format.
True or False?

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Usage of '-' in eval command.

Hi, I am trying to use eval command to evaluate a variable(HAPROXY_LISTENER_rabbitmq_project-test-BRHM_PORT) which consists of '-' but unfortunately the eval command is unable to interpret the value of variable and trims the variable name after '-' and produces the string output rather than the... (10 Replies)
Discussion started by: Kuldip
10 Replies

2. Shell Programming and Scripting

Error in eval eval command to print html tags

anyone has any info on why this is complaining??? vivek@vivek-c5e55ef2e ~/TAC $ zoneCounter=1 vivek@vivek-c5e55ef2e ~/TAC $ optUsage1=23% vivek@vivek-c5e55ef2e ~/TAC $ eval eval echo "<th>Zone $zoneCounter </th><th align=\"left\"> \$optUsage$zoneCounter </th>" -bash: syntax error... (13 Replies)
Discussion started by: vivek d r
13 Replies

3. Shell Programming and Scripting

Error in eval eval command to print html tags

anyone has any info on why this is complaining??? vivek@vivek-c5e55ef2e ~/TAC $ zoneCounter=1 vivek@vivek-c5e55ef2e ~/TAC $ optUsage1=23% vivek@vivek-c5e55ef2e ~/TAC $ eval eval echo "<th>Zone $zoneCounter </th><th align=\"left\"> \$optUsage$zoneCounter </th>" -bash: syntax error... (1 Reply)
Discussion started by: vivek d r
1 Replies

4. Shell Programming and Scripting

Help with perl eval command .....

Hi All, I read the above written code (perl code) in another perl script and evaluates this code for each line of text file,but using exit statement in code make this not to work and i could not get the desired results. However if i use return it works fine. I just need to know why it doesn't... (1 Reply)
Discussion started by: sarbjit
1 Replies

5. Shell Programming and Scripting

Eval command help

I have file called myfile which has the text "myserver" in it. I need to have a command to ping "myserver". How would I do that? I tried when I type at the terminal I get the output as . How do I do something like a ? thanks, Nick (5 Replies)
Discussion started by: nikhilfake
5 Replies

6. Shell Programming and Scripting

[bash] command line substitution with environmental variables

Hi, I'm using an array that contains compiler FLAGS that need to be executed either before ./configure or after the main 'make' command. example of array containing compiler flags. ------------------------------------------------- FLAGS="CFLAGS=\"-arch x86_64 -g -Os -pipe... (7 Replies)
Discussion started by: ASGR
7 Replies

7. UNIX for Dummies Questions & Answers

Expanding variables with Ed Bash 3.2.33

Hi, The following code finds the line containing fruits in test.txt and replaces instances of apple with banana. ed -s test.txt <<< $’/fruits/s/apple/banana/g\nw’ What I want to do is put variables in the place of fruits, apple and banana. I have tried replacing ' with " to get... (2 Replies)
Discussion started by: de_la_espada
2 Replies

8. Shell Programming and Scripting

'who' command -- getting data returned into variables (in bash)

Anyone know how to get the data out of the "who" command? I'm still in lukewarm pursuit of creating an OS X-like welcome message at the start of any Terminal session, sans having to use either bash login or calling up ssh. My trials & errors and surfing around have narrowed it down for me... (1 Reply)
Discussion started by: SilversleevesX
1 Replies

9. Shell Programming and Scripting

Bash 'shopt' doubt

Hi, I am using bash shell's extended pattern matching. What tweak the following code needs in order to get the expected output? shopt -s extglob f="a@b@_c@d@_e" echo "${f/@(@|@_)/__}" My expected output is: a__b__c__d__e but the actual output is: a__b@_c@d@_e # that is, how to... (3 Replies)
Discussion started by: royalibrahim
3 Replies

10. Shell Programming and Scripting

Access to database/eval command

Hi i have the following code: if(($line!=1) and (@field!='\$')){ print ( "\nTRY TO CONNECT TO DATABASE................\n"); my $dbh = DBI->connect($dsn, $user, $pass); print ("CONNECTED TO DATABASE\n"); eval ... (1 Reply)
Discussion started by: chriss_58
1 Replies

Featured Tech Videos