2012-02-12 13 views
1

ファイルまたはディレクトリをソースディレクトリからコピー先ディレクトリに移動し、シンボリックリンクをソースディレクトリに置くbashスクリプトを作成しようとしています。Bash:ファイル/ディレクトリを移動してリンクを作成する

したがって、<source_path>はファイルまたはディレクトリです。<destination_dir_path>は元のファイルを移動したいディレクトリです。

使用例:

$ mvln /source_dir/file.txt /destination_dir/ 
OR 
$ mvln /source_dir/dir_I_want_to_move/ /destination_dir/ 

これは、私が一緒に入れて管理しているものですが、それが正常に動作しません。

mv: unable to rename `/source_dir/some_file.txt': Not a directory 

とディレクトリをdestination_directoryとに移動されていないだけで、その内容が移動されています それはエラーを返しますそれ以外の場合は、MV、ソースがディレクトリである場合にのみ機能します。

#!/bin/bash 

SCRIPT_NAME='mvln' 
USAGE_STRING='usage: '$SCRIPT_NAME' <source_path> <destination_dir_path>' 

# Show usage and exit with status 
show_usage_and_exit() { 
    echo $USAGE_STRING 
    exit 1 
} 

# ERROR file does not exist 
no_file() { 
    echo $SCRIPT_NAME': '$1': No such file or directory' 
    exit 2 
} 

# Check syntax 
if [ $# -ne 2 ]; then 
    show_usage_and_exit 
fi 

# Check file existence 
if [ ! -e "$1" ]; then 
    no_file $1 
fi 

# Get paths 
source_path=$1 
destination_path=$2 

# Check that destination ends with a slash 
[[ $destination_path != */ ]] && destination_path="$destination_path"/ 

# Move source 
mv "$source_path" "$destination_path" 

# Get original path 
original_path=$destination_path$(basename $source_path) 

# Create symlink in source dir 
ln -s "$original_path" "${source_path%/}" 

何人かお手伝いできますか?

+2

「正しく動作しません」と定義します。 –

+0

はい、質問を編集しました。ありがとうございました。 – Reggian

+0

これまでスクリプトをテストしたことがうまくいっているようです。 – Sujoy

答えて

4

問題は、$destination_pathが存在しないディレクトリを参照していることです。このような何か:

mv /path/to/file.txt /path/to/non/existent/directory/ 

はエラーを返し、

mv /path/to/directory/ /path/to/non/existent/directory/ 

/path/to/non/existent/directory/から/path/to/directory//path/to/non/existent/がちょうどdirectoryという名前のサブフォルダせず、存在しないディレクトリであることを提供する)の名前を変更します。

あなたは$destination_pathが存在しないことを期待している場合は、あなたがmkdirコマンドを追加することができます

mkdir "$destination_path" 
mv "$source_path" "$destination_path" 

あなたはそれが存在しない可能性があることを期待している場合に、あなたは条件付きでそれを追加することができます:

[[ -d "$destination_path" ]] || mkdir "$destination_path" 
mv "$source_path" "$destination_path" 

を、あなたはそれが存在しないことを期待しているならば、あなたは行うには、いくつかのデバッグを持っています!

(ちなみに、あなたの正確な状況に応じて、あなたが有用であることがmkdir -pを見つけるかもしれない。それは、再帰的にディレクトリすべての必要な親ディレクトリを作成し、ディレクトリがすでに存在する場合、それは気にしません。)

+0

それはトリックでした。ありがとうございました! – Reggian

+0

@Reggian:ようこそ! – ruakh

+0

ああ、私もディレクトリが作成されました!ナイスキャッチ – Sujoy

関連する問題