Search code examples
bashshellls

bash script calling ls worked perfectly until I renamed the directory the script runs in


I wrote a bash script in /home/maxg/SpProData. It ran just fine. The target machine's directory for the script is called /home/maxg/sppro

In order to test the script on the machine it was written on, I renamed it from /home/maxg/SpProData to /home/maxg/sppro.

I changed the home directory variable for the script, and it gets now stuck at where an ls command result is passed into a variable, like so:

_WORKING_ZIP=$(ls -td ${_SP_LINK_CFG_FILENAME}_${_PERF_DIR_NAME_PREFIX}Archive_${_TODAY_VARIANT}_* | head -1)

resulting in:

[info ] Looking for the PerformanceDataArchive (.zip) file ...
find ............. ArgyleCourt_PerformanceDataArchive_2020-05-09_*
ls: cannot access 'ArgyleCourt_PerformanceDataArchive_2020-05-09_*': No such file or directory
[error] (2) = ls had a more serious problem; e.g. directory or file not found... exiting!

The constants are:

SP-LINK cfg file name...: ArgyleCourt
Perf DIR name prefix....: PerformanceData
Today variant...........: 2020-05-09
SP PRO directory........: /home/maxg/sppro

The file exist:

drwxrwxr-x  3 maxg maxg  4096 May 16 19:59 .
drwxr-xr-x 56 maxg maxg  4096 May 16 19:33 ..
-rw-r--r--  1 maxg maxg 55477 May  9 02:03 ArgyleCourt_PerformanceDataArchive_2020-05-09_02-03-07.zip
-rw-rw-r--  1 maxg maxg 56208 May 15 22:27 GetSpProData.awk
-rw-rw-r--  1 maxg maxg  1511 May 16 19:52 GetSpProData.conf
-rwxrwxr-x  1 maxg maxg 23530 May 16 20:04 GetSpProData.sh

Running the command in the terminal returns the desired result:

ls ArgyleCourt_PerformanceDataArchive_2020-05-09_*
ArgyleCourt_PerformanceDataArchive_2020-05-09_02-03-07.zip

This makes no sense at all. Only two changes were made:

  1. rename the directory
  2. change the home directory constant to point to the new name.

... later on:

I changed the directory name (and variable) back to SpProData, same non-working result.

... later on:

Copied the scrip to the target machine and it runs! (Looks like a long night) :(


Solution

  • You are giving a relative path instead of an absolute path.

    Try

    
    _WORKING_ZIP=$(ls -td /home/maxg/sppro/${_SP_LINK_CFG_FILENAME}_${_PERF_DIR_NAME_PREFIX}Archive_${_TODAY_VARIANT}_* | head -1)
    

    Edit: Also don't parse ls

    You can use

    
    _WORKING_ZIP=$(head -1 <<< /home/maxg/sppro/${_SP_LINK_CFG_FILENAME}_${_PERF_DIR_NAME_PREFIX}Archive_${_TODAY_VARIANT}_*)
    

    Example :

    $ls my_file_is_here.txt
    ls: cannot access 'my_file_is_here.txt': No such file or directory
    $ls ~/test/my_file_is_here.txt
    /home/renegade/test/my_file_is_here.txt
    $cd ~/test/
    $ls my_file_is_here.txt
    my_file_is_here.txt
    $