๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ฒœ์ฒœํžˆ, ๊พธ์ค€ํžˆ../C

[C : echo] ํ„ฐ๋ฏธ๋„๋กœ ์ž…๋ ฅ๋ฐ›์€ ๊ฐ’ ์ถœ๋ ฅํ•˜๊ธฐ #argc #argv

by MIMI.L 2023. 12. 16.
๋ฐ˜์‘ํ˜•

echo๋ฅผ c์–ธ์–ด๋กœ ๊ตฌํ˜„ํ•ด๋ณด๊ณ ์ž ํ•จ !

mimi@mimi:~/Mimi/lang/c$ echo aaa bbb ccc
aaa bbb ccc

 

๋ช…๋ น๊ณผ ํ•จ๊ป˜ ์ž…๋ ฅ๋ฐ›์€ ์ธ์ž๋“ค์„ ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅํ•ด์ฃผ๊ธฐ !

 

์ž…๋ ฅ๋ฐ›์€ ์ธ์ž์˜ ๊ธธ์ด๋Š” ์–ด๋–ป๊ฒŒ ์•Œ์ง€ ? int argc

์ž…๋ ฅ๋ฐ›์€ ์ธ์ž์˜ ๋‚ด์šฉ์€ ์–ด๋–ป๊ฒŒ ์•Œ์ง€ ? char* argv[] (๋˜๋Š” char** argv)

 

๊ทธ๋Ÿผ ์ด๊ฑธ ์–ด๋–ป๊ฒŒ ์“ฐ์ง€ ?

main ํ•จ์ˆ˜์—์„œ int argc์™€ char* argv[] ๋ฅผ ์ธ์ž๋กœ ๋ฐ›๋„๋ก ์ž‘์„ฑํ•˜๊ธฐ !

#include <stdio.h>

int main(int argc, char* argv[]) {
    // ์ฝ”๋“œ์ž‘์„ฑ
    return 0;
}

 

argc๋Š” ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ํ„ฐ๋ฏธ๋„์—์„œ ๋ช…๋ น์œผ๋กœ ์ž…๋ ฅ๋œ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด์ฃผ๊ณ 

argv๋Š” ์ž…๋ ฅ๋œ ๋‚ด์šฉ์„ ๋ฌธ์ž์—ด๋กœ ์ €์žฅํ•ด์„œ ๊ฐ€์ง€๊ฒŒ ๋จ !

 

argc๋Š” ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด์ฃผ๋Š” ์ˆซ์ž๋‹ˆ๊นŒ int,

argv๋Š” ๋ฌธ์ž์—ด์„ ์ €์žฅํ•ด์ฃผ๋‹ˆ๊นŒ ๋ฌธ์ž์—ด ์ด์ค‘ํฌ์ธํ„ฐ char* [] (๋˜๋Š” char**) ์‚ฌ์šฉ !

 

์ฐธ๊ณ ๋กœ, ํ„ฐ๋ฏธ๋„์—์„œ ์ž…๋ ฅ๋˜๋Š”๊ฑธ ๋ฐ›์•„์ฃผ๋Š”๊ฑฐ๋ผ ํŒŒ์ผ๋ช…๋ถ€ํ„ฐ ๋ฐ›์•„์ค€๋‹ค.

๋”ฐ๋ผ์„œ, argv[0] ์—๋Š” ํŒŒ์ผ๋ช…์ด ๋“ค์–ด๊ฐ !

mimi@mimi:~/Mimi/lang/c$ ./echo hello world !
argc : 4 
argv : hello world ! 
argv[0] : ./echo 
argv[1] : hello 
argv[2] : world 
argv[3] : !
๋”๋ณด๊ธฐ

์œ„ ๋‚ด์šฉ์„ ๋งŒ๋“  ํŒŒ์ผ !

์ปดํŒŒ์ผ์€ ์ด๋ ‡๊ฒŒ gcc echo.c -o echo ํ–ˆ์Œ

#include <stdio.h>

int main(int argc, char** argv) {
    
    int i = 0;
    
    printf("argc : %d \n", argc);
    printf("argv : ");
    for (i=1; i<argc; i++) {
        printf("%s ", argv[i]);
    }
    printf("\n");
    for (i=0; i<argc; i++) {
        printf("argv[%d] : %s \n", i, argv[i]);
    }
    return 0;
}โ€‹

๊ทธ๋ž˜์„œ ๋‚˜๋Š” echo.c๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ๋งŒ๋“ค์—ˆ์Œ !

#include <stdio.h>

int main(int argc, char* argv[]) {
    int i = 0;
    for (i=1; i<argc; i++) {
        printf("%s ", argv[i]);
    } 
    printf("\n");
    return 0;
}

 

์ปดํŒŒ์ผ ํ›„ ์‹คํ–‰ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด...

mimi@mimi:~/Mimi/lang/c$ ./echo aaa bbb ccc
aaa bbb ccc 
mimi@mimi:~/Mimi/lang/c$

 

 


 

echo ๋ช…๋ น์–ด๋Š”

".." ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ฐ’์„ ์ถœ๋ ฅํ•ด์ฃผ๊ณ 

'..' ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฌธ์ž์—ด ๊ทธ๋Œ€๋กœ๋ฅผ ์ถœ๋ ฅํ•ด์คŒ

๋”ฐ๋ผ์„œ ๋‹ค์Œ๋ฒˆ์—” ' " ๊ตฌ๋ถ„ํ•ด์„œ ์ถœ๋ ฅํ•ด์ฃผ๋„๋ก ๊ตฌํ˜„ํ•ด๋ณด๊ณ ์ž ํ•จ

 

์œ„ ๋‚ด์šฉ์€ ์‰˜์—์„œ ์ฒ˜๋ฆฌํ•ด์ฃผ๋‚˜๋ด ! ๊ทธ๋ƒฅ ๋‚ด๊ฐ€ ๋งŒ๋“ ๊ฑธ๋กœ๋„ ๋œ๋‹น

mimi@mimi:~/Mimi/lang/c$ ./echo "Hello ${HOME}"
Hello /home/mimi 
mimi@mimi:~/Mimi/lang/c$ ./echo 'Hello ${HOME}'
Hello ${HOME}

 

๋‹ค์Œ๋ฒˆ์—” ls ๋งŒ๋“ค๊ธฐ ๋„์ „

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€