gxtaillon
gxtaillon

Reputation: 1076

Cannot evaluate script arguments from function

I've started writing shell scripts again and I've found myself in a situation where I frequently have to write debug echo's to trace what the script is doing. The, easy, way I used to do this right was to write something like this :

#!/bin/bash
myVar = 'Erractic Nonesense'
echo "myVar: $myVar" 

==> myVar: Erractic Nonesense

This worked great and was fairly simple but, having to write this for every variable I wished to trace was tiring and as a person who thinks that having less code to do more stuff is great, I wrote myself a function:

#!/bin/bash
dbg() # $msg
{
    echo "$@: ${!@}" 
}

myVar = 'Erractic Nonesense'
dbg myVar

==> myVar: Erractic Nonesense

This works great for regular variables but, for the scripts arguments ($1, $2, etc.), does not work. Why?

==> $ ./myScript 123

#!/bin/bash
...
dbg 1 # This is the bugger in question.

==> 1: 1

And also, how can this be circumvented?

EDIT

Thanks to Barmar I now see why it behaves this way but, the second question remains.

EDIT 2

Using koodawg idea, this is the result. It works. Updated, see EDIT 4

EDIT 3

I think that a mix of EDIT 2 and set +-x will be a viable solution.

EDIT 4

Updated the logic to fall on arguments as the previous one did not always worked. Added fancy tabs.

RX_INTEGER='^[0-9]+$'
DBG_SCRIPT_ARGS=( "$0" "$@" )
DBG_PADDING="        " # tabs of 8 spaces
dbg() # $msg | OUT$args OUT$res
{    
    args=$@
    [[ $args =~ $RX_INTEGER ]] && res="${DBG_SCRIPT_ARGS[args]}" || res="${!@}"
    printf "%s%s\`%s\`\n" "$args:" "${DBG_PADDING:$(((${#args}-1)%${#DBG_PADDING}))}" 
}

Upvotes: 4

Views: 365

Answers (1)

GL2014
GL2014

Reputation: 6704

You would have to call the function and explicitly pass the script args to it. You could do something like:

for argz in `echo $*`
do
    dbg ${argz}
done

Upvotes: 1

Related Questions