To find out the directory in which a shell script file resides, you can use the dirname
command with the $0
variable, which contains the name of the script file.
For example, to print the directory in which the script file resides, you can use the following command:
refer to:lautturi.comecho $(dirname $0)
This will print the directory in which the script file is located.
The dirname
command returns the directory component of a file path. When used with the $0
variable, it returns the directory in which the script file is located.
You can also use the pwd
command to print the current working directory. For example:
echo $(pwd)
This will print the current working directory, which is the directory from which the script was executed.
Keep in mind that the pwd
command only works if the script was executed from the current working directory. If the script was executed from a different directory, the pwd
command will not return the directory in which the script file resides. In that case, you can use the dirname
command as shown above.
You can use these commands to set a variable containing the directory in which the script file resides. For example:
SCRIPT_DIR=$(dirname $0)
This will set the SCRIPT_DIR
variable to the directory in which the script file is located. You can then use the SCRIPT_DIR
variable in your script to reference files or directories in the script's directory.
For example, to reference a file named config.txt
in the script's directory, you can use the following command:
config_file="$SCRIPT_DIR/config.txt"
This will set the config_file
variable to the full path of the config.txt
file, using the SCRIPT_DIR
variable to reference the script's directory.