I make a script for backup'a databases. And it does not work for the sql files to go side by side in the current folder. How can this be implemented without absolute paths?

#!/bin/bash current_dir=$(pwd) mysqldump -u***** -p***** --databases db_name > $current_dir/db_name/$(date +"%Y-%m-%d").sql 

When running via crontab, writes Unknown command current_dir How to be?

  • what exactly is not working for you? What exactly do you want to accomplish by assigning non-directory values ​​to the PATH variable? - aleksandr barakin
  • I thought sh and bash are runtimes. I have already been told that pwd will not work from crontab. - Anton
  • it is not a "medium". bash is a program. sh is a symbolic link (however, also to a program). PATH is an environment variable . pwd is an internal shell command. naturally, it works. so what's not working for you? - aleksandr barakin
  • Message to internal mail unknown command current_dir - Anton
  • And how then can you make, for example, files go to a folder next to the script? - Anton

2 answers 2

from the comments, it became clear that by “current directory” the author means the directory in which the script itself is located.

usually, the path to the shell script (containing the name of the script itself) is passed to the script itself as a “zero” parameter: $0 .

extract the directory path from it, i.e. discard the file name (with the script), the easiest way is using the dirname program (quotes should be used in case there are special characters like $0 in $0 ):

 current_dir=$(dirname "$0) 

in principle, this is already enough to address the directory, but in case the script is run with an indication of a relative path (for example, ./скрипт ), and you need to get an absolute path, you can use the realpath program:

  abs_path=$(realpath "$(dirname "$0")") 

    Try this way to get the path to the executable script:

     current_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"