BASH: variable and function scope and subscripts


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting BASH: variable and function scope and subscripts
# 1  
Old 09-30-2013
BASH: variable and function scope and subscripts

Hi,

I'm a Delphi developer new to linux, new to this forums and new to BASH programming and got a new task in my work: maintaining an existing set of BASH scripts. First thing I want to do is making the code more reliable as in my opinion it's really bad written. So here's the quest:

I'm using an EXIT-trap for cleaning up after a script. For this task I used the Idea from http://www.linuxjournal.com/content/use-bash-trap-statement-cleanup-temporary-files (I'm not yet allowed to post URLs) which defines a function to add to a list of statements to be executed on EXIT called add_on_exit. A second function (on_exit) is registered in the trap and executes the statements added in reverse order. To this point it's all clear to me and working in the first script.

Now I want to re-use this functions. The system consists of 3 parts: The 2 functions and the array. I'm not completely sure about the scope and when the triggering events occur. Here is what I found so far (please confirm or refute):
  • Functions and variables are valid till the shell closes.
  • The EXIT "signal" is fired whenever the script ends (in contrast to the validity of the functions and parameters).
  • When a script is called by executing the file, it is executed in the shell of the caller. (not sure how to check this - Edit: According to cero: If the file is executed by calling the file it opens a new shell for execution, if it's sourced it executes in the existing shell - thanks for clarification!)
  • When a script is executed by cron, the script is executed in a new shell which is closed afterwards (not sure how to check this)
  • Calling a script that does nothing but defining functions lets me use them in my script after the call. (doesn't seem to work: functions don't seem to be defined after the call - Edit: source them works, thanks to jim mcnamara)
  • I can pass a global variable "by reference" to a function by passing the name of the variable and using it with eval (confirmed through tests)
Things that are still unclear to me:
  • Is it safe to redefine the on_exit function (e.g. on a subscript) while a trap is set (i.e. between the first call to add_on_exit and the end of the script)?
Last but not least here's the actual code I'm planning to use:
  • Script with the functions (lets call it defineexittrapfuncs):
    Code:
    #!/bin/bash
    
    function on_exit {
      # evaluate statements in passed array in reverse order
      eval 'for ((i=${#'$1'[*]}-1; i>=0; i--)); do eval ${'$1'[$i]}; done'
    }
    
    function add_on_exit {
      local items_array="$1" # name of the array with statements
      shift
      eval 'local n=${#'$items_array'[*]}' # number of already existing statements in the array
      if [[ $n -eq 0 ]]; then
        eval $items_array'[$n]="unset '$items_array'"' # first unset the array (evaluated last)
        ((n++))
      fi
      eval $items_array'[$n]="$@"' # append new statement
      if [[ $n -eq 1 ]]; then # create trap, if this was the first added statement
        eval "trap 'on_exit "$items_array"' EXIT" # on_exit gets called whenever the script ends, regardless of the end-reason
      fi
    }

  • Script that would make use of the EXIT-trap (edited according to the answer of jim mcnamara):
    Code:
    #!/bin/bash
    
    MUTEX=/tmp/mutex_`basename ${0}`
    EXISTS=`basename ${0}`': Mutex vorhanden'
    declare -a on_exit_items
    
    source ./defineexittrapfuncs # for testing it's in the same directory
    
    if [ -f $MUTEX ]; then
      echo -e "\n$EXISTS\n"
      exit 0
    else
      date +%s > $MUTEX
      add_on_exit on_exit_items rm "$MUTEX"
      echo 'script is doing something'
    fi


Last edited by rse; 10-07-2013 at 04:50 AM..
# 2  
Old 09-30-2013
One point:
Code:
Calling a script that does nothing but defining functions lets me use them in my script after the call. (doesn't seem to work: functions don't seem to be defined after the call)

You have to source external files that simply define variables/functions, ex: foo.shl
Code:
#! /bin/bash

# method 1
source ./path/to/foo.shl
# method 2
.  ./path/to/foo.shl

Note the leading dot, followed by a space
This User Gave Thanks to jim mcnamara For This Post:
# 3  
Old 09-30-2013
Quote:
Originally Posted by jim mcnamara
You have to source external files that simply define variables/functions
Thanks for that important hint! I adapted my first post according to that.
# 4  
Old 10-02-2013
Since there are no further replies I assune that all my other findings are not wrong and I will implement it that way.
# 5  
Old 10-02-2013
This is not completely correct:
"When a script is called by executing the file, it is executed in the shell of the caller. (not sure how to check this)"

Not sure what you mean with "called by executing the file", but unless you source it a script starts a subshell which terminates when the script ends. That's why functions and variables are not defined after execution (see jims post).
This User Gave Thanks to cero For This Post:
# 6  
Old 10-07-2013
Quote:
Originally Posted by cero
... unless you source it a script starts a subshell which terminates when the script ends. That's why functions and variables are not defined after execution (see jims post).
That makes perfect sense to me. I assume the first line in the script, the shebang, opens the new shell for execution.

Again, I edited my first post. Thanks very much!

RSE

p.s. Sorry for the delay, there was an official holiday on thursday and I didn't check from at home.
# 7  
Old 10-07-2013
The shebang does not open the new shell, it just defines what is used to process the script. Usually it says which shell should be used, but the shebang does not have to point to a shell.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Bash Variable scope - while loop while reading from a file

Cope sample1: test.sh i=0 echo " Outside loop i = $i " while do i=$(( $i + 1)) echo "Inside loop i = $i " done echo " Out of loop i is : $i " When run output : Outside loop i = 0 Inside loop i = 1 Inside loop i = 2 Inside loop i = 3 Inside loop i = 4 Inside loop i = 5 Inside... (8 Replies)
Discussion started by: Adarshreddy01
8 Replies

2. Shell Programming and Scripting

Bash function using variable in it syntax error

The below bash function uses multiple variables CODING, SAMPLE, SURVEY, andvariant in it. The user selects the cap function and details are displayed on the screen using the $SURVEY variable, the directory is changed to $SAMPLE and the samples.txt is opened so the user can select the sample to... (6 Replies)
Discussion started by: cmccabe
6 Replies

3. Programming

Variable Scope in Perl

I have to admit that i have not used Perl at all and this is a singular occasion where i have to patch an existing Perl script. I dearly hope i do not have to do it again for the next 15 years and therefore try to avoid having to learn the programming language in earnest. The OS is AIX 7.1, the... (2 Replies)
Discussion started by: bakunin
2 Replies

4. Shell Programming and Scripting

Variable scope in bash

Hello! Before you "bash" me with - Not another post of this kind Please read on and you will understand my problem... I am using the below to extract a sum of the diskIO on a Solaris server. #!/bin/sh PATH=/usr/bin:/usr/sbin:/sbin; export PATH TEMP1="/tmp/raw-sar-output.txt$$"... (3 Replies)
Discussion started by: haaru
3 Replies

5. UNIX for Dummies Questions & Answers

Bash loops and variable scope

Hi All, I've been researching this problem and I am pretty sure that the issue is related to the while loop and the piping. There are plenty of other threads about this issue that recommend removing the pipe and using redirection. However, I haven't been able to get it working using the ssh and... (1 Reply)
Discussion started by: 1skydive
1 Replies

6. Shell Programming and Scripting

Scope of exported function

Hi I'm hoping someone can tell me how to extend the scope of an exported function in the korn shell. I have written a function in a file that I dot in from my .kshrc file and it works fine. However I would like this function to be available to anyone in a certain group on the machine... (10 Replies)
Discussion started by: steadyonabix
10 Replies

7. Shell Programming and Scripting

variable scope

Hi, I want to know about the variable scope in shell script. How can we use the script argument inside the function? fn () { echo $1 ## I want this argument should be the main script argument and not the funtion argument. } also are there any local,global types in shell script? if... (3 Replies)
Discussion started by: shellwell
3 Replies

8. Shell Programming and Scripting

scope of the variable - Naga

Hi All, I am new to unix shell scripting, in the below script "num" is an input file which contains a series of numbers example : 2 3 5 8 I want to add the above all numbers and want the result finally outside the while loop. it prints the value zero instead of the actual expected... (13 Replies)
Discussion started by: nagnatar
13 Replies

9. Shell Programming and Scripting

Bash: how to call function having it's name in variable?

Hello. Looking for a method of modularizing my bash script, I am stuck with such a problem. For example, I have: MODULE_NAME="test" FUNCTION_NAME="run" How do I can a function with name test_run? (4 Replies)
Discussion started by: FractalizeR
4 Replies

10. Shell Programming and Scripting

$0 scope in function and calling script

Hi folks, I'm just running through an oreilly korn shell book but have witnessed an output difference on my own unix machine and the output provided in the book. Can anyone help? create a script called ascript as follows: function afunc { print in function $0: $1 $2 var1="in... (16 Replies)
Discussion started by: beckett
16 Replies
Login or Register to Ask a Question