現在のディレクトリシェルスクリプトから別の名前のファイルをコピーする

現在のディレクトリシェルスクリプトから別の名前のファイルをコピーする

私のバッシュスクリプト

echo -n "Round Name:"
read round
mkdir $round

echo -n "File Names:"
read $1 $2 $3 $4 $5 $6
cp ~/Documents/Library/Template.py $1.py $2.py $3.py $4.py $5.py $6.py .

ディレクトリの自動化があり、ファイル名に対しても同じ自動化が必要です。

不明な入力を受け取った後にこれを行うには、どのようにシェルスクリプトを取得しますか?
cp ~/Documents/Library/Template.py A.py B.py C.py D1.py D2.py $round/.

ベストアンサー1

さまざまな文字列を対話形式で読み取るのではなく、スクリプトのコマンドラインからユーザーに渡すようにしてください。

以下のスクリプトが呼び出されます。

./script -d dirname -t templatefile -- string1 string2 string3 string4

dirname...まだ存在しない場合は、生成されたtemplatefile文字列で指定されたルート名を使用してディレクトリにコピーされます。テンプレートファイルにファイル名のサフィックスがある場合は、各文字列の末尾に追加して新しいファイル名を作成します(既存のサフィックスの重複を避けるために文字列からサフィックスを削除した後)。

オプションを使用すると、スクリプト内のディレクトリ作成手順を上書きできます-n。この場合、スクリプトは指定されたディレクトリが-dすでに存在すると仮定します。

#!/bin/sh

# Unset strings set via options.
unset -v dirpath do_mkdir templatepath

# Do command line parsing for -d and -t options.
while getopts d:nt: opt; do
    case $opt in
        d)
            dirpath=$OPTARG
            ;;
        n)
            do_mkdir=false
            ;;
        t)
            templatepath=$OPTARG
            ;;
        *)
            echo 'Error in command line parsing' >&2
            exit 1
    esac
done

shift "$((OPTIND - 1))"

# Sanity checks.
: "${dirpath:?Missing directory path (-d)}"
: "${templatepath:?Missing template file path (-t)}"

if [ ! -f "$templatepath" ]; then
    printf 'Can not find template file "%s"\n' "$templatepath" >&2
    exit 1
fi

if "${do_mkdir-true}"; then
    # Create destination directory.
    mkdir -p -- "$dirpath" || exit
fi
if [ ! -d "$dirpath" ]; then
    printf 'Directory "%s" does not exist\n' "$dirpath" >&2
    exit 1
fi

# Check to see whether the template file has a filename suffix.
# If so, save the suffix in $suffix.
suffix=${templatepath##*.}
if [ "$suffix" = "$templatepath" ]; then
    # No filename suffix.
    suffix=''
else
    # Has filename suffix.
    suffix=.$suffix
fi

# Do copying.
for string do
    # Remove the suffix from the string,
    # if the string ends with the suffix.
    string=${string%$suffix}
    cp -- "$templatepath" "$dirpath/$string$suffix"
done

質問の最後にある例を再生成するには、次のようにこのスクリプトを使用できます。

./script -t ~/Documents/Library/Template.py -d "$round" -- A B C D1 D2

おすすめ記事