简体   繁体   English

如何使用调用 shell 脚本的目录?

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

I am trying to make a script to automate the creation of files and input of certain data in the files, sort of like a template.我正在尝试制作一个脚本来自动创建文件并在文件中输入某些数据,有点像模板。 For example, if the script is called cpp (Just an example, not the actual script name), when I run cpp <filename> it should create a file in the current directory without me having to tell it what the directory is.例如,如果脚本名为cpp (只是一个示例,不是实际的脚本名称),当我运行cpp <filename>时,它应该在当前目录中创建一个文件,而无需我告诉它目录是什么。 Right now, I have to hard code a root directory into the script.现在,我必须将根目录硬编码到脚本中。 The basic functionality of the script is something like this (I have validations and stuff, but this is the main function):脚本的基本功能是这样的(我有验证和东西,但这是主要功能):

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"

In this situation, I have to declare the file path to be FILE_PATH="$HOME/<a specific directory>/$1.cpp" , meaning when I call on the script, I have to pass an argument relative to the hard-coded location, like perhaps cpp automation/file_manager/shell/apartment .在这种情况下,我必须将文件路径声明为FILE_PATH="$HOME/<a specific directory>/$1.cpp" ,这意味着当我调用脚本时,我必须传递一个相对于硬编码的参数位置,例如cpp automation/file_manager/shell/apartment Is there a way for a shell script to automatically find the directory it is called on, so it can be more dynamic and flexible (Go to the directory automation/file_manager/shell/apartment and call cpp apartment to get the same result)?有没有办法让 shell 脚本自动找到调用它的目录,这样它可以更加动态和灵活(转到目录 automation/file_manager/shell/apartment 并调用cpp apartment得到相同的结果)? Kind of like vim or neovim, where it creates a file in the current directory.有点像 vim 或 neovim,它在当前目录中创建一个文件。

You can use您可以使用

    `dirname $0`
in your bash script. 在您的 bash 脚本中。 This would take the value of the directory where your script is placed. 这将采用放置脚本的目录的值。 You would be able to execute your bash from anywhere as long as you have the right access. 只要您有正确的访问权限,您就可以从任何地方执行您的 bash。

Good practice:良好做法:

 #initiate the dir name dir=`dirname $0` #initiate the name of your file file="my_filename" #use as needed: # create file in current bash directory touch $dir/$file # append echo -e "my_cpp_script" >> $dir/$file #call cpp $dir/$file #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