2011-05-13 44 views
6

我正在研究一個基於ffmpeg的小應用程序,並且我讀了一個tutorial made for ubuntu,他們建議在生成的可執行文件上使用命令hash使用'hash'命令

我很好奇這個命令,你有沒有用過它?爲此目的?

當我在我的源文件夾中運行它,我得到這個(編譯一次)

$ hash 
hits command 
    1 /usr/bin/strip 
    1 /usr/local/bin/ffmpeg 
    1 /usr/bin/svn 
    4 /usr/local/bin/brew 
    2 /usr/bin/git 
    1 /bin/rm 
    1 /bin/cat 
    1 /usr/bin/ld 
    1 /bin/sh 
    4 /usr/bin/man 
    5 /usr/bin/make 
    4 /usr/bin/otool 
    15 /bin/ls 
    6 /usr/bin/open 
    2 /usr/bin/clear 

看起來像我的.bash_history的總結......

當我在一個可執行文件運行它,我做沒有顯示很多行,並且該應用程序中似乎沒有任何更改?

$ md5 ffserver 
MD5 (ffserver) = 2beac612e5efd6ee4a827ae0893ee338 
$ hash ffserver 
$ md5 ffserver 
MD5 (ffserver) = 2beac612e5efd6ee4a827ae0893ee338 

當我尋找男人時,它只是說它是一個內建函數。真的很有用:)

在Linux和MacOSX上它確實有效(比如說存在)。

感謝您的幫助,我可能會學到今天:)

回答

8

hash其實不是你的歷史的東西;它是一個bash(1)殼內置維持最近執行的程序的哈希表(從bash(1)

Bash uses a hash table to remember the full pathnames of 
    executable files (see hash under SHELL BUILTIN COMMANDS 
    below). A full search of the directories in PATH is 
    performed only if the command is not found in the hash table. 

引導你發現可能表明運行它只是爲了看看ffmpeg命令將在下一步執行;也許有一個由配送包裝提供的ffmpeg程序,並且他們想要確保新的應用程序將被執行而不是發行版提供的程序,如果您只是在shell中鍵入ffmpeg

這似乎是一個舒展,因爲它會需要具有含在PATHffmpeg之前的發行提供的版本的目錄,而且也不能保證情況。

+0

酷,謝謝......我還是不明白,爲什麼我應該編譯後使用,因爲我平時在$ PATH不進行編譯。 – Rob

+1

@Rob,同意了,這對我來說似乎很奇怪。我認爲我在使用Unix或Linux系統十五年或十六年後曾經需要一次散列,這可能是由於我當時缺乏經驗。 – sarnold

+0

另請參閱http://unix.stackexchange.com/questions/86012/what-is-the-purpose-of-the-hash-command –

6

如果您使用的命令可能未安裝在系統上,請檢查其可用性並告訴用戶缺少的內容。從Scripting with style

例子:

NEEDED_COMMANDS="sed awk lsof who" 

missing_counter=0 
for needed_command in $NEEDED_COMMANDS; do 
    if ! hash "$needed_command" >/dev/null 2>&1; then 
    printf "Command not found in PATH: %s\n" "$needed_command" >&2 
    ((missing_counter++)) 
    fi 
done 

if ((missing_counter > 0)); then 
    printf "Minimum %d commands are missing in PATH, aborting" "$missing_counter" >&2 
    exit 1 
fi