我最近發現了一個用於隱藏桌面文件和資料夾的腳本。以下是腳本:
#!/bin/bash
#
cd /home/ramvignesh/Desktop
for f in `ls`; do
mv "$f" ".$f"
done
該腳本無法正常運作。它不會隱藏其中以空格命名的檔案。例如,如果我有一個名為“無標題文檔”的文件,我會收到以下錯誤。 。 。
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