簡體   English   中英

如何使用調用 shell 腳本的目錄?

[英]How to use the directory a shell script is called from?

我正在嘗試制作一個腳本來自動創建文件並在文件中輸入某些數據,有點像模板。 例如,如果腳本名為cpp (只是一個示例,不是實際的腳本名稱),當我運行cpp <filename>時,它應該在當前目錄中創建一個文件,而無需我告訴它目錄是什么。 現在,我必須將根目錄硬編碼到腳本中。 腳本的基本功能是這樣的(我有驗證和東西,但這是主要功能):

touch "$FILE_PATH" (this is the part that I have to hard code)
echo -e "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\t\n}" > "$FILEPATH"
nvim "$FILE_PATH"

在這種情況下,我必須將文件路徑聲明為FILE_PATH="$HOME/<a specific directory>/$1.cpp" ,這意味着當我調用腳本時,我必須傳遞一個相對於硬編碼的參數位置,例如cpp automation/file_manager/shell/apartment 有沒有辦法讓 shell 腳本自動找到調用它的目錄,這樣它可以更加動態和靈活(轉到目錄 automation/file_manager/shell/apartment 並調用cpp apartment得到相同的結果)? 有點像 vim 或 neovim,它在當前目錄中創建一個文件。

您可以使用

    `dirname $0`
在您的 bash 腳本中。 這將采用放置腳本的目錄的值。 只要您有正確的訪問權限,您就可以從任何地方執行您的 bash。

良好做法:

  #initiate the dir name dir=`dirname $0` #initiate your file name file="my_filename" #use as needed: # 在當前 bash 目錄中創建文件 touch $dir/$file # append echo -e "my_cpp_script" > > $dir/$file #call cpp $dir/$file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM