简体   繁体   English

C程序中的bash脚本代码

[英]bash script code inside C program

my problem is the following: I have this bash script: 我的问题如下:我有这个bash脚本:

#!/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. 我需要将此代码插入C程序中 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. 我试图用一行代码重新编写所有脚本,然后直接使用shell测试它,并且可以正常工作,但是我遇到了引号问题,并且转义试图将其用作system()调用的参数。 Can you suggest me a way out? 你能建议我出路吗?

Thank you for your help 谢谢您的帮助

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 通过system()调用来调用临时脚本
  4. Delete the temporary file 删除临时文件

However, consider this as a last resort. 但是,将此作为最后的选择。

Put it into a shell script and invoke the shell script from your C code. 将其放入外壳脚本中,然后从您的C代码中调用外壳脚本。 Much easier to maintain IMHO. 维护恕我直言要容易得多。

#define SHELLSCRIPT "
...
write your shell script code here
...
"



   int main()
    {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM