ファイルを隠すためのスクリプト

ファイルを隠すためのスクリプト

最近、デスクトップのファイルとフォルダを非表示にするスクリプトを見つけました。以下がそのスクリプトです。

#!/bin/bash
#
cd /home/ramvignesh/Desktop
for f in `ls`; do
mv "$f" ".$f"
done

スクリプトが正しく動作していません。スペースを含む名前のファイルは非表示になりません。たとえば、「Untitled Document」という名前のファイルがある場合、次のエラーが発生します。

mv: cannot stat ‘Untitled’: No such file or directory
mv: cannot stat ‘Document’: No such file or directory

スクリプトがなぜこのように動作するのか教えてください。誰かスクリプトを修正してもらえませんか? よろしくお願いします。

答え1

見つかったスクリプトは、コマンドの出力を解析する際に欠陥があります(スクリプトでls使用すべきでない理由については、こちらをご覧ください)。lsここ)。

より良い方法は、findコマンドを使用してその出力を にパイプすることですxargs

元のスクリプトでは特定のディレクトリにあるファイルを操作していたため、それに応じてコマンドを調整しました。ファイルを非表示にするディレクトリに移動し、以下の部分を実行します。

find . -maxdepth 1 -type f ! -name ".*" -printf "%f\0" | xargs -0 -I file mv file .file

これは私のホーム ディレクトリにある小さなデモです。3 つのファイルを作成し、上記のコマンドを使用してそれらを非表示にします。

$ touch file1 file2 file3


$ find . -maxdepth 1 -type f ! -name  ".*" -printf "%f\0" | xargs -0 -I file mv file .file 


$ ls -a
./             .bash_logout  Desktop/    .file1   .gnupg/        .macromedia/  Pictures/  .ssh/        .xsession-errors
../            .bashrc       .dmrc       .file2   .ICEauthority  .mkshrc       .profile   Templates/   .xsession-errors.old
.adobe/        .cache/       Documents/  .file3   .lesshst       .mozilla/     .psensor/  Videos/
.bash_history  .config/      Downloads/  .gconf/  .local/        Music/        Public/    .Xauthority

上記はファイルに対して機能します。ディレクトリに対して機能させるには、-type fに変更するだけです-type d

デモ:

$ ls
dirone/  dirthree/  dirtwo/


$ find . -maxdepth 1 -type d ! -name  ".*" -printf "%f\0" | xargs -0 -I file mv file .file                                                           


$ ls


$ ls -a
./  ../  .dirone/  .dirthree/  .dirtwo/

答え2

renameと という名前の小さなスクリプトを使用しますhide_desktop_files

#!/bin/bash
dir="$PWD"
cd ~/Desktop
rename 's/(.*)/.$1/' *
cd "$dir"

% ls -ogla ~/Desktop
total 92
drwxr-xr-x   3  4096 Aug 15 20:45 .
drwxr-xr-x 236 86016 Aug 15 20:46 ..
-rw-rw-r--   1     0 Aug 15 20:45 bar
-rw-rw-r--   1     0 Aug 15 20:45 foo
drwxrwxr-x   2  4096 Aug 15 20:45 .foo

% ./hide_desktop_files                
rename(bar, .bar)
foo not renamed: .foo already exists

% ls -ogla ~/Desktop
total 92
drwxr-xr-x   3  4096 Aug 15 20:45 .
drwxr-xr-x 236 86016 Aug 15 20:47 ..
-rw-rw-r--   1     0 Aug 15 20:45 bar
-rw-rw-r--   1     0 Aug 15 20:45 foo
drwxrwxr-x   2  4096 Aug 15 20:45 .foo

関連情報