shell script 기초

yo·2021년 8월 5일
0

1. Writing your first shell script

  • A shell script is text file that contains a series of commands
  • any work you can do on the command line can ba automated by a shell script
  • day1.sh 파일을 아래처럼 만들어보자.
#!/bin/bash
echo "I don't have to be great to start, but I have to start to be great!"
  • ./day1.sh 로 방금 만든 파일을 실행하면 아래같은 에러가 난다.
  • zsh: permission denied: ./day1.sh
  • 파일 실행 권한이 없기 때문인데, 아래 명령으로 실행 권한을 주자.
  • chmod +x day1.sh
    • +x는 execute(실행)권한을 의미힌다.
  • 이제 다시 ./day1.sh로 실행하면 아래처럼 출력된다.
  • I don't have to be great to start, but I have to start to be great!

ls -l으로 권한 확인하기

  • ls -l day1.sh로 권한을 확인하면 아래와 같다.
    • -rwxr-xr-x 1 hwanil staff 87 Aug 4 16:44 day1.sh
    • r: read
    • w: write
    • x: execute
    • -: 제일 앞에 '-'는 file임을 나타낸다. 이게 d라면 directory를 의미함.
    • 제일 앞 '-' 뒤 3개는 파일 owner, 그 뒤 3개는 group, 마지막 3개는 everyone on the system의 권한 의미
  • execute하기 위해선 read, execute권한을 가지고 있어야 한다.
    • 실행하기 위해선 읽어야 하기 때문.
    • 권한 설정 바꿨는데도 실행이 안되면 chmod +rx day1.sh명령어를 실행해보자.

2. Shell builtin commands

  • 쉘스크립트는#!로 시작하는데, 저 두 캐릭터를 shebang이라 부르기도 한다.
    • #가 sharp으로 불리기도 하고, !가 bang으로 불리기 때문에 합쳐서 shebang
  • /bin/bash는 interpreter다.
  • #!/bin/bash를 명시하지 않으면 script는 current shell interpreter로 실행된다.
  • 이유는 잘 이해가 안되는데, 여튼 이걸 명시하지 않으면 여러 사람이 여러 환경에서 이 파일을 실행할 때 일관된 결과가 나오지 않고 에러가 날 수 있다.
  • 따라서 항상 #!/bin/bash를 명시해주자.
  • 파일 실행은 ./day1.sh 혹은 /home/jason/day1.sh식으로 가능하다.
  • echo는 파이썬의 print같은 역할. 빌트인임.
  • 어떤 command가 builtin인지 확인하려면 type을 사용하면 된다.
    • type echo
    • 출력: echo is a shell builtin
  • echo의 모든 instance를 보려면 type -a echo를 사용
    • 출력:
      echo is a shell builtin
      echo is /bin/echo

variable

  • 아래 내용으로 day2.sh를 만들자.
#!/bin/bash
SKILL="shell scripting"
echo "I want to be good at ${SKILL}. That's why I practice ${SKILL}"
  • 주의할 점은 =전후로 스페이스바가 없는 것.
  • chmod +x day2.sh, chmod +x day2.sh실행시 결과는 아래와 같다.
  • 출력: I want to be good at shell scripting. That's why I practice shell scripting

3. Variables, comments and capitalization

#!/bin/bash
WORD="script"
echo "${WORD}ing is fun"
echo "$WORDing is fun"
  • 출력결과:

    scripting is fun
    is fun
    
  • uppercase가 convention이다. 항상 대문자로 쓰자.

  • 변수를 사용하는 방법은 두가지다.

  • ${VARIABLE} 형태로 사용이 가능하고,

  • $VARIABLE 형태로도 가능하다. {}를 생략.

  • 하지만 변수 바로 뒤에 다른 문자를 이어 쓴다면 {}를 꼭 써줘야 한다. 안그러면 어디서부터 어디까지가 변수인지 몰라 의도한 대로 작동하지 않는다.

  • 위 예시에서 $WORDing은 아예 없는 변수로 취급받아 인식 자체가 안됐다.

  • 주석은 #를 사용하여 표시한다.

4. Writing long and complicated scripts

5. Making decision in your scripts and using builtin shell variables

  • got-root.sh라는 파일을 만들어보자.
#!/bin/bash

# Determine if the user executing this script is the root use or not.

# Display the UID
echo "Your UID is ${UID}."

# Display if the user is the root user or not.
if [[ "${UID}" -eq 0 ]]
then
  echo "You are root."
else
  echo "You are not root"
fi
  • if문과 [[, ]] 사이에는 각각 최소 스페이스바 1칸이 필요하다. (문법)

  • -eq: equal의 뜻이다.

    • -ne: not equal
    • -lt: less than
  • if문 뒤에 [를 하나만 써도 되지만, 그건 old version. 두개 쓰는게 최신 버전이므로 항상 두개를 쓰자.

  • 위 파일 실행결과는 아래와 같다.

  • Your UID is 501.
    You are not root
  • root유저의 UID는 항상 0이다.

  • root유저로 실행하려면 sudo를 사용하면 된다. sudo ./got-root.sh

  • 결과:

      Your UID is 0.
      You are root.

출처: udemy강의 (intro to Linux Shell Scripting(free course))

profile
Never stop asking why

0개의 댓글