0

I want to save a copy of the bash file each time I run it. It should be saved to the output dictionary. I am doing it like this in the mytrainrtest.sh file:

mkdir -p "${EXP_DIR}/train"
cp "${WORK_DIR}"/mytrainrtest.sh "${EXP_DIR}"/.

Now I have much more bash files with name my****** as copies of the upper one, each with different names.

How can I write the line, so the bash file will recognize its name to copy itself?

zheyuanWang
  • 1,158
  • 2
  • 16
  • 30
  • Why do you need to make a copy every time you run it? Are you somehow *modifying* the script as it runs? – chepner Jul 20 '20 at 13:28
  • There are a plethora of options available. The easiest is to save the name of the script in one of the first lines of the script like `scriptsource="$(readlink -f "$0")"`. and then make the copy as `cp "$scriptsource" "${EXP_DIR}"/`. Other options, but less generic are the use of `"${BASH_SOURCE[1]}"`. All are explained in the proposed duplicate. (note the usage of `readlink -f` as I am not aware where in the script you use the `cp` and if you already did a couple of `cd to/random/path` in there or not.) – kvantour Jul 20 '20 at 13:31
  • yes, I modify the scripts all the time when debugging. After that I also change the input dictionary,quite often – zheyuanWang Jul 20 '20 at 14:08

2 Answers2

1

Use the $0 special variable which contains the name of the currently executing script.

cp "$0" "$exp_dir"/
choroba
  • 231,213
  • 25
  • 204
  • 289
  • thanks, `cp "${WORK_DIR}"/"${0}" "${EXP_DIR}"/.` worked for me – zheyuanWang Jul 20 '20 at 14:11
  • The `$0` contains the relative path to the script from the directory from which you started it. If you `cd` somewhere else, it might be better to use `readlink -f $0` at the beginning of the script to fetch the absolute path so you don't depend on the content of $PWD at the start of the script. – choroba Jul 20 '20 at 14:14
0

Script name(path) stored in a special var $0

#!/bin/bash
echo $0

$ ./test
./test
Ivan
  • 6,188
  • 1
  • 16
  • 23