[bash] Executing script that is held in a variable


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting [bash] Executing script that is held in a variable
# 8  
Old 01-16-2010
First of all, you should use single quotes when assigning to the array variables or escape the inner double quotes. Also, you are intermingling ARRAY and array.

Try:
Code:
#!/bin/bash
ARRAY[0]='#!/usr/bin/perl -w'
ARRAY[1]='use strict;'
ARRAY[2]='print "Hello, Perl!\n";'

To use other interpreters than bash you have to somehow invoke those interpreters. One way would be to use the contents of the shebang:

Code:
eval "${ARRAY[0]#\#!}" <(printf "$script")

-or-
Code:
printf "$script" | eval "${ARRAY[0]#\#!}"


Last edited by Scrutinizer; 01-16-2010 at 12:25 PM..
# 9  
Old 01-17-2010
Fantastic.

Should have seen the intermingling but I was working from
several examples and ended up copy/pasting from several
scripts.

Thanks to both jlliagre and Scrutinizer for all your help.

For future reference, these scripts work:
Code:
#!/bin/bash
ARRAY[0]='#!/usr/bin/python'
ARRAY[1]='print "Hello, Python!"'

IFS="
 "

script="$(echo "${ARRAY[*]}")"
eval "${ARRAY[0]#\#!}" <(printf "$script")

and
Code:
#!/bin/bash
ARRAY[0]='#!/usr/bin/perl -w'
ARRAY[1]='use strict;'
ARRAY[2]='print "Hello, Perl!\n";'

IFS="
 "

script="$(echo "${ARRAY[*]}")"
eval "${ARRAY[0]#\#!}" <(printf "$script")



---------- Post updated at 07:55 AM ---------- Previous update was at 06:21 AM ----------

Just a small problem.

The function that loads and assigns the array that contains the
script seems to imply double quotes. Is their a quick method
that could be built into a function to convert each element of
an array from double quotes to single quotes. Or if possible, to
include it within the eval statement.

I tried putting single quote escape characters around ARRAY
but that didn't seem to work.

A.

Last edited by ASGR; 01-17-2010 at 08:01 AM.. Reason: update
# 10  
Old 01-17-2010
Maybe we are making this too complicated. If I have an input file like so:

Code:
# cat infile
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
[script-nameofscript]
#!/usr/bin/perl -w
use strict;
print "Hello, Perl!\n";
[/script-nameofscript]
This is line 10
This is line 11
This is line 12
This is line 13
This is line 14

And if I use a script like this:
Code:
#!/bin/bash
script=""
shebang=""
reading_script=0
while IFS= read -r line
do
  if [[ $reading_script -eq 1 ]]; then
    if [[ $line == "[/script-"* ]]; then
      reading_script=0
      eval "${shebang#\#!}" <(printf "$script")
      script=""
      shebang=""
    else
      script="$script$line"
    fi
  else
    if [[ $line == "[script-"* ]]; then
      reading_script=1
      IFS= read -r shebang
    else
      printf "$line\n"
    fi
  fi
done < infile

Then the output is:
Code:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
Hello, Perl!
This is line 10
This is line 11
This is line 12
This is line 13
This is line 14

Or is that not what you had in mind?

---------- Post updated at 14:39 ---------- Previous update was at 14:16 ----------

Slightly optimized script:
Code:
#!/bin/bash
reading_script=false
while IFS= read -r line
do
  case $line in
    "[/script-"*)
       reading_script=false
       eval "${shebang#\#!}" <<< $script
       script=""; shebang="" ;;
    "[script-"*)
       reading_script=true
       IFS= read -r shebang ;;
    *)
       if $reading_script; then
         script="$script$line"
       else
         printf "$line\n"
       fi ;;
  esac
done < infile



---------- Post updated at 14:42 ---------- Previous update was at 14:39 ----------

Posix compliant version:
Code:
#!/bin/sh
reading_script=false
while IFS= read -r line
do
  case $line in
    "[/script-"*)
       reading_script=false
       printf "$script" | eval "${shebang#\#!}"
       script=""; shebang="" ;;
    "[script-"*)
       reading_script=true
       IFS= read -r shebang ;;
    *)
       if $reading_script; then
         script="$script$line"
       else
         printf "$line\n"
       fi ;;
  esac
done < infile

# 11  
Old 01-17-2010
This is an extract from the project,
Code:

#!/bin/bash
################################################################################
function array_append	{ eval "$1=( \"\${$1[@]}\" \"\${$2[@]}\" )"; }
function array_assign	{ eval "$1=( \"\${$2[@]}\" )"; }
function array_rm_front { eval "$1=( \"\${$1[@]##$2}\" )"; }
function array_loads	{ local IFS=$'\n'; eval "$1=( \$( < \"$2\" ) )"; }
function array_script	{ local IFS=$'\n'; eval "\${$1[0]#\#!} <(printf \${$1[*]:1} )"; }
function string_assigns	{ eval "$1=( \"\$2\" )"; }
################################################################################
function tag_filters
{
	local -a	_FLTR_SRC_;	array_assign	_FLTR_SRC_	$2
	local		_FLTR_TAG_;	string_assigns	_FLTR_TAG_	$3
	local		_FLTR_APP_;	string_assigns	_FLTR_APP_	"false"
	local -a	_FLTR_RTN_

	for _LINE_ in "${_FLTR_SRC_[@]}"; do

	case $_LINE_ in
	\[$_FLTR_TAG_\]		)	_FLTR_APP_=true;;
	\[*\]			)	_FLTR_APP_=false;;
	*			)	;;
	esac

	case $_FLTR_APP_ in
	true			)	array_append	_FLTR_RTN_	_LINE_;;
	*			)	continue;;
	esac

	done
	array_assign $1 _FLTR_RTN_
}
################################################################################
function array_defrag
{
	local -a	_DFRG_SRC_;	array_assign	_DFRG_SRC_	$1
	local -a	_DFRG_RTN_
	for _ITEM_ in "${_DFRG_SRC_[@]}"; do
	if [ -n "$_ITEM_" ]
		then	array_append _DFRG_RTN_ _ITEM_
		else	continue
		fi
	done
	array_assign	$1	_DFRG_RTN_
}
################################################################################
# MAIN
################################################################################
	declare	-a	_file_cfg_ _file_tmp_

	array_loads	_file_cfg_	"/where/script/file/is"
	tag_filters	_file_tmp_	_file_cfg_ "script-python"
	array_rm_front	_file_tmp_	'##'*			# remove remarks
	array_rm_front	_file_tmp_	'['*			# remove tags
	array_defrag	_file_tmp_				# defrag array
	array_script	_file_tmp_				# execute script

And this is an example of a data file that would contain tags including
scripts as well as others. The location of which has to be specified in
the variable above.
Code:

[different-tags]
################################################################################
## LOCAL SCRIPTS
################################################################################
[script-bash]
#!/bin/bash
declare -i INT=10
for (( i=0 ; i<INT ; i++ )); do
	echo "Hello, Bash!"
	done
################################################################################
[script-perl]
#!/usr/bin/perl -w
use strict;
print "Hello, Perl!\n";
################################################################################
[script-python]
#!/usr/bin/python
print "Hello, Python!"
################################################################################
[more-different-tags]

The sections don't have a corresponding closing tag. They are terminated
with either another tag or end of file, handled by the 'for' loop in the
'tag_filters' function. It was designed to take wildcards so that similar
tags would be filtered and then the contents of the array could be
refined and/or appended to each other with another function.
Conveniently, it also takes absolutes.

Getting back to the problem... I'm still experiencing problems with
incomplete commands, due to the lack of single quotes around the
elements of the array. The whole process is programatically applied
and I have no opportunity to manually insert single quotes around the
elements of the array.

To solve the problem, I was wondering if it was possible to somehow
incorporate the single quote solution into the 'array_script' command
so that whenever a script is invoked, it is processed there.

Alternatively, an acceptable solution would be a function that converts
an array so that each element is surround by single quotes just before
the 'array_script' function is called.

I hope the above is more informative.

A.
# 12  
Old 01-17-2010
Hi ASGR, you could give this a try:
Code:
function array_script   { local IFS=$'\n'; eval "\${$1[0]#\#!} <(printf \"\${$1[*]}\")"; }

I removed the :1 and added the escape inner double quotes.

---

I think the script you provided is perhaps a tad difficult to read. I am not convinced arrays are the way to go since IMO plain variables will serve that same purpose just fine. Also I am not sure if the abundant use of functions together with call by name paramter passing through the eval mechanism adds much to the clarity of the script.

---

FWIW, based on your latest input file specifications I created the following example script for you to use as a comparison:
Code:
#!/bin/sh
reading_script=false
while IFS= read -r line
do
  case $line in
    "[script-"*)
       if $reading_script; then
         printf "$script" | eval "${shebang#\#!}"
         script=""; shebang=""
       fi
       reading_script=true
       IFS= read -r shebang
    ;;
    "["*)
       reading_script=false
       printf "$script" | eval "${shebang#\#!}"
       script=""; shebang=""
    ;;
    *) if $reading_script; then
         script="$script$line\n"
       else
         printf "$line\n"
       fi
    ;;
  esac
done < infile
if $reading_script; then
  printf "$script" | eval "${shebang#\#!}"
fi

Output:
Code:
################################################################################
## LOCAL SCRIPTS
################################################################################
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Bash!
Hello, Perl!
Hello, Python!

And here is the same script using a plain function with global variables and no parameters passing:
Code:
#!/bin/sh
exec_script()
{
  if $READING_SCRIPT; then
    printf "$SCRIPT" | eval "${SHEBANG#\#!}"
    SCRIPT=""; SHEBANG=""
  fi
}

READING_SCRIPT=false
while IFS= read -r line
do
  case $line in
    "[script-"*)
       exec_script
       READING_SCRIPT=true
       IFS= read -r SHEBANG
    ;;
    "["*)
       exec_script
       READING_SCRIPT=false
    ;;
    *) if $READING_SCRIPT; then
         SCRIPT="$SCRIPT$line\n"
       else
         printf "$line\n"
       fi
    ;;
  esac
done < infile
exec_script

S.
# 13  
Old 01-17-2010
Thanks for reply.

I'll review the code when I have a chance.

Just to explain the method behind the madness, I'm trying
to create a reusable library of functions that is majority
array related.

Whilst consulting with a fellow forum user, it was determined
that using 'eval' was the best, if not only, solution to assign
and return arrays from functions. From there-on everything
became eval based for the sake of consistency.

A.
# 14  
Old 01-18-2010
The consequence of using bash and arrays with functions is the use of name passing through eval. I think that you can probably also build those functions on the basis of plain variables and the read shell builtin. I think it is just a matter of preference. The use of variables is merely an alternative approach that may lead to simpler code..

Last edited by Scrutinizer; 01-18-2010 at 03:52 AM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Executing sed command inside a bash script

I want to run commands inside a bash script. An example is I want to pass the command in a string as regexp as an argument to the script, then run sed on the bash variable sed.sh regexp sed.sh "-i \"s/<p>//g\"" then call sed "$regexp" $fl (3 Replies)
Discussion started by: Kangol
3 Replies

2. Shell Programming and Scripting

Bash script if condition not executing

issue is with .txt files (7 Replies)
Discussion started by: anil529
7 Replies

3. Shell Programming and Scripting

Acces Variable from expect-Script in bash-Script

Hi all, I have a little problem with a expect in a bash Script. The hull of my script: #!/bin/sh ( expect -c ' set a \"eee\"; # the variable a ' ) echo $a; # using the variable out of the expect script I would like to use the variable out of the expect script(in bash),... (3 Replies)
Discussion started by: gandalfthepink
3 Replies

4. UNIX for Dummies Questions & Answers

Write pid and command name to a txt file while executing a bash script

Hi All, Just have a requirement, I am executing a bash shell script, my requirement is to catch the pid and job name to a txt file in the same directory, is there anyway to do it? please help me out. Regards Rahul ---------- Post updated at 08:42 AM ---------- Previous update was at... (2 Replies)
Discussion started by: rahulkalra9
2 Replies

5. Shell Programming and Scripting

Bash script errors when executing

I'm working on a script that will search through a directory for MKV files and remux them to MP4. I found a few other scripts around the net that do this, but they all have limitations that don't always get the job done. The main limitation I've found is that most scripts look for the video track... (2 Replies)
Discussion started by: rayne127
2 Replies

6. Shell Programming and Scripting

variable issue in a bash in a shell script

Hi, I am trying to write a PBS shell script that launches a bash process. The issue is that the bash process needs a variable in it and the shell script is interpreting the variable. How do I pass this as a literal string? Here is my code snippit: TMP=".fasta" FILEOUT=$FILE$TMP cd... (2 Replies)
Discussion started by: bioBob
2 Replies

7. Shell Programming and Scripting

passing variable from bash to perl from bash script

Hi All, I need to pass a variable to perl script from bash script, where in perl i am using if condition. Here is the cmd what i am using in perl FROM_DATE="06/05/2008" TO_DATE="07/05/2008" "perl -ne ' print if ( $_ >="$FROM_DATE" && $_ <= "$TO_DATE" ) ' filename" filename has... (10 Replies)
Discussion started by: arsidh
10 Replies

8. Shell Programming and Scripting

How do you parse a variable in a bash script?

I have a script I use on my web server (Apache2). I am changing to Lighttpd and need to make a few changes. This is what I use on my apache server #!/bin/bash # accepts 3 parameters: <domain name> <user name> <XXXXXXXX> # domain name is without www (just domain.com) # username would be... (3 Replies)
Discussion started by: vertical98
3 Replies

9. Shell Programming and Scripting

Trying to create variable, value not being held

I tried creating a variable with the awk command. The correct value is being printed to the screen; however, the variable max is not being set. The command "echo $max" is null. Any help would be greatly appreciated. Thank you. cat test.txt: -rw-r--r-- 1 root root 0 2005-01-12 20:51... (2 Replies)
Discussion started by: cstovall
2 Replies

10. Shell Programming and Scripting

Finding out the length of a string held within a variable

:confused: Does anyone know which command I can use to find out the length of a string held within a variable? (5 Replies)
Discussion started by: dbrundrett
5 Replies
Login or Register to Ask a Question