0

my problem is the following: I have this bash script:

#!/bin/bash

 IFSBAK=$IFS
 if [ "$TXTEXT" = "" ]; 
 then
   CMD="find . -iname \"*.txt\" -or -iname \"*.text\""
 else
CMDTEMP="find . "
IFS=":"
for i in $TXTEXT
do
    CMDTEMP="${CMDTEMP} -iname \"*.${i}\" -or"
done
IFS=$IFSBAK
CMD=${CMDTEMP%-or}
 fi

 FILES=$(eval $CMD)
 OUTPUT=$1

 for f in $FILES
 do
VAR=$(grep -ae [a-zA-Z0-9] "$f" | tr -cs "[:alnum:]" "\n")
IFS=$' \n\t-?=!*][.\",();\'\`\´:'   
for v in $VAR
do
    echo $v >> "${OUTPUT}"
done
IFS=$' \n\t'
 done

and I need to insert this code inside a C program. I've tried to re-write the all script on a single line testing it directly with the shell and it works, but I'm having problems with quotes and escaping trying to use it as a parameter of the system() call. Can you suggest me a way out?

Thank you for your help

4
  • 6
    seems like a mighty bad idea to insert that much shell code into binary Commented Apr 1, 2011 at 18:37
  • 3
    +1 @Anycom - anytime you think you need to do something like embed a 30 line shell script in your program, you need to rethink your design. Commented Apr 1, 2011 at 18:38
  • 1
    i already know it's an horrible thing to do, but i am forced to do it as requested. thank you anyway Commented Apr 1, 2011 at 18:47
  • How exactly are you forced to do this? Is the requirement really that absolute and specific, or is it indirect? There might be other ways, depending... Commented Apr 1, 2011 at 19:42

3 Answers 3

4

If you really have no choice but to deliver a single binary and you cannot ship the shell script file with the binary consider the following:

  1. Include the contents of the script in a single literal
  2. During execution of the program, print the contents of the literal to a temporary file. You probably need some strategy to come up with a unique filename.
  3. Call the temporary script through system() call
  4. Delete the temporary file

However, consider this as a last resort.

Sign up to request clarification or add additional context in comments.

Comments

3

Put it into a shell script and invoke the shell script from your C code. Much easier to maintain IMHO.

2 Comments

How would you access functions in a Linux shell script from C code?
@abc You can't. You call the shell script as an external executable and then read the output.
1
#define SHELLSCRIPT "
...
write your shell script code here
...
"



   int main()
    {

        system(SHELLSCRIPT);
        return 0;
        //put the bash to C program 
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.