[SUPINFO][Linux] Bash Scripting

박현아·6일 전

SUPINFO

목록 보기
11/11

1 - Archive

Write a script that creates a tarball of a given user home directory. The script can take the username as argument; otherwise, the script will prompt for it. The archive will be stored in /tmp with the date in the file name.

요구사항 정리:

  • 사용자 이름을 인자로 받기
  • 인자가 없으면 프롬프트로 입력받기
  • 해당 사용자의 홈 디렉토리를 tar로 압축
  • /tmp 에 저장
  • 파일 이름에 날짜 포함

1) archive.sh 파일 생성

$ nano archive.sh
#!/bin/bash

# 1. 사용자 이름이 인자로 들어왔는지 확인
if [ -n "$1" ]; then
    USERNAME="$1"
else
    read -p "Enter username: " USERNAME
fi

# 2. 홈 디렉토리 경로 설정
HOME_DIR="/home/$USERNAME"

# 3. 사용자가 존재하는지 확인
if [ ! -d "$HOME_DIR" ]; then
    echo "Error: User home directory does not exist."
    exit 1
fi

# 4. 날짜 생성 (YYYYMMDD 형식)
DATE=$(date +%Y%m%d)

# 5. 아카이브 파일 이름 설정
ARCHIVE_NAME="/tmp/${USERNAME}_home_${DATE}.tar.gz"

# 6. tarball 생성
tar -czf "$ARCHIVE_NAME" "$HOME_DIR"

# 7. 완료 메시지
echo "Archive created: $ARCHIVE_NAME"

2) 실행 권한 주기

$ chmod +x archive.sh

3) 인자없이 실행

$ ./archive.sh

이름 입력

4) 결과

hyunah@hyunah-VMware-Virtual-Platform:~$ ./archive.sh
Enter username: hyunah
tar: Removing leading `/' from member names
tar: /home/hyunah/.cache/ibus/dbus-WE4vOIwr: socket ignored
tar: /home/hyunah/.cache/ibus/dbus-YBwpaXcG: socket ignored
tar: /home/hyunah/.cache/ibus/dbus-0DB5uqCN: socket ignored
tar: /home/hyunah/.cache/ibus/dbus-rMCaQ34F: socket ignored
Archive created: /tmp/hyunah_home_20260303.tar.gz

2 - TBBT

You have just ripped off a DVD of the first season of one of your favorite TV shows. The files are named as "Chapter XX.avi". You want to get all these files renamed as "XX - Episode name.avi". Write a script that reads episode names from a eplist.txt file (one episode per line, sorted chronologically):
Pilot
The Big Bran Hypothesis
The Fuzzy Boots Corollary
The Luminous Fish Effect
The Hamburger Postulate
The Middle-Earth Paradigm
The Dumpling Paradox
The Grasshopper Experiment
The Cooper-Hofstadter Polarization
The Loobenfeld Decay
The Pancake Batter Anomaly
The Jerusalem Duality
The Bat Jar Conjecture
The Nerdvana Annihilation
The Pork Chop Indeterminacy
The Peanut Reaction
The Tangerine Factor
This file does not contain episode numbers, only titles. The script should compute new names for each file, show a renaming proposition and ask user for confirmation before actually renaming.

요구사항 정리:

  • 현재 파일명: Chapter XX.avi
  • 변경할 파일명: XX - Episode name.avi
  • 에피소드 제목은 eplist.txt에서 한 줄씩 읽음
  • 실제 변경 전에 미리 보여주고 사용자 확인 받기

1) eplist.txt 생성

nano eplist.txt
Pilot
The Big Bran Hypothesis
The Fuzzy Boots Corollary
The Luminous Fish Effect
The Hamburger Postulate
The Middle-Earth Paradigm
The Dumpling Paradox
The Grasshopper Experiment
The Cooper-Hofstadter Polarization
The Loobenfeld Decay
The Pancake Batter Anomaly
The Jerusalem Duality
The Bat Jar Conjecture
The Nerdvana Annihilation
The Pork Chop Indeterminacy
The Peanut Reaction
The Tangerine Factor

2) rename.sh 생성

nano rename.sh
#!/bin/bash

# TBBT Episode Rename Script
# 기존 파일이 없어도 제안 출력 가능

EPFILE="eplist.txt"

# 1. eplist.txt 존재 확인
if [ ! -f "$EPFILE" ]; then
    echo "Error: $EPFILE not found."
    exit 1
fi

# 2. eplist.txt 라인 수
EP_COUNT=$(wc -l < "$EPFILE")

echo "Proposed renaming:"
echo "-------------------"

i=1
declare -a OLD_NAMES
declare -a NEW_NAMES

# 3. 제안 계산 및 출력 (파일 없어도)
while IFS= read -r TITLE; do
    OLD_NAME=$(printf "Chapter %02d.avi" "$i")
    NEW_NAME=$(printf "%02d - %s.avi" "$i" "$TITLE")

    echo "$OLD_NAME  ->  $NEW_NAME"

    # 실제 rename를 위해 배열에 저장
    OLD_NAMES+=("$OLD_NAME")
    NEW_NAMES+=("$NEW_NAME")

    ((i++))
done < "$EPFILE"

echo
read -p "Proceed with renaming if files exist? (y/n): " ANSWER

if [[ "$ANSWER" =~ ^[Yy]$ ]]; then
    # 실제 파일이 있을 경우만 rename
    for idx in "${!OLD_NAMES[@]}"; do
        if [ -f "${OLD_NAMES[$idx]}" ]; then
            mv "${OLD_NAMES[$idx]}" "${NEW_NAMES[$idx]}"
        fi
    done
    echo "Renaming completed for existing files."
else
    echo "Operation cancelled."
fi

3) 실행 권한 주기

$ chmod +x rename.sh

4) 실행

$ ./rename.sh

5) 결과

hyunah@hyunah-VMware-Virtual-Platform:~$ ./rename.sh
Proposed renaming:
-------------------
Chapter 01.avi  ->  01 - Pilot.avi
Chapter 02.avi  ->  02 - The Big Bran Hypothesis.avi
Chapter 03.avi  ->  03 - The Fuzzy Boots Corollary.avi
Chapter 04.avi  ->  04 - The Luminous Fish Effect.avi
Chapter 05.avi  ->  05 - The Hamburger Postulate.avi
Chapter 06.avi  ->  06 - The Middle-Earth Paradigm.avi
Chapter 07.avi  ->  07 - The Dumpling Paradox.avi
Chapter 08.avi  ->  08 - The Grasshopper Experiment.avi
Chapter 09.avi  ->  09 - The Cooper-Hofstadter Polarization.avi
Chapter 10.avi  ->  10 - The Loobenfeld Decay.avi
Chapter 11.avi  ->  11 - The Pancake Batter Anomaly.avi
Chapter 12.avi  ->  12 - The Jerusalem Duality.avi
Chapter 13.avi  ->  13 - The Bat Jar Conjecture.avi
Chapter 14.avi  ->  14 - The Nerdvana Annihilation.avi
Chapter 15.avi  ->  15 - The Pork Chop Indeterminacy.avi
Chapter 16.avi  ->  16 - The Peanut Reaction.avi
Chapter 17.avi  ->  17 - The Tangerine Factor.avi

Proceed with renaming if files exist? (y/n): y
Renaming completed for existing files.

0개의 댓글