[UNIX CLI] Command Line(4)

1 minute read


UNIX COMMAND LINE

  • UNIX CLI 정리(4)
  • bash : shell script 수행
  • $@ : bash를 통해 shell script를 실행할 때 변수를 받을 수 있게 함
  • for : for loop

bash

  • bash [shell_script_name]을 통해 shell script(shell 명령어만 폼한된 텍스트 파일)의 명령어를 실행
    • shell script는 주로 [file_name].sh로 저장
# command를 입력할 shell script를 vim을 이용해 생성
vim print_header.sh

# print_header.sh 안에 수행할 명령어 입력
head -n 1 iris.csv

# bash [file_name]을 통해 명령어 수행
bash print_header.sh

# history 명령어를 활용하면 이전에 수행한 명령어들을 쉽게 텍스트 파일로 만들 수 있음
# history | tail -n [number_of_lines].sh > [shell_script_name].sh

$@

  • 지정하고 싶은 변수가 복수일 때는 $1, $2 등으로 가능
# print_header.sh 안에 수행할 명령어 입력
head -n 1 $@

# bash [file_name]을 통해 명령어 수행
bash print_header.sh iris.csv
 
# row number을 2 번째로 변수로, 파일 이름을 첫 번째 변수로 지정
head -n $2 $1
bash print_header.sh iris.csv 1

multiple lines in shell script

# multiple commands
# print the total row numbers and the column name of csv files that starts with c in the directory
vim print_row_column_name.sh

wc -l $@
head -n 1 $@

bash print_row_column_name.sh c*.csv

for loop in shell script

  • for [i] in [names] do [functions] done
# multiple commands
# print the total row numbers and the column name of csv files that starts with c in the directory
vim print_row_column_name.sh

for file in $@
do
    wc -l $file
    head -n 1 $file
done

bash print_row_column_name.sh c*.csv

# print the total row numbers of csv files that start with c and sort the number of rows as ascending
vim print_row_num.sh

for file in $@
do
    wc -l $file
done

bash print_row_num.sh c*.csv | sort