繁体   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