linux system 執行shell腳本傳參數的問題。。。

問題:

我寫的shell程序傳入的參數是
s1 s2都是字符串。
s1是 -P 22 /home/
s2是/home

這樣在程序中,直接system調用的話,會出現只把-P 22分別給了s1,s2,怎麼處理這個問題,讓-P 22 /home/
傳給s1,/home傳給s2?


解決方法:

使用system調用的話,必須使用字符串;

如下:
char str[1024];
char a1[] = "-P 22 /home/";
char a2[] = "/home";
sprintf(str, "a.sh \"%s\" \"%s\"", a1, a2);
system(str);

這樣就可以了;

實驗驗證:

a1.sh

#/bin/bash
#ls |wc -l
echo change_pppoe.sh '$1='$1--'$2'=$2


a1.c

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX 1024
#define PATH "~/a/home/a1.sh"

int main()
{
     FILE *fp;
     char buffer[MAX];
     sprintf(buffer, "~/a/home/a1.sh \"i am a girl!\" \"this is\"");
     printf("%s\n", buffer);
     system(buffer);
}

輸出:
[root@bogon home]# ./a1
~/a/home/a1.sh "i am a girl!" "this is"
change_pppoe.sh $1=i am a girl!--$2=this is

驗證完全正確


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章