1

I have a script done in Bash which runs a file on the folder where the script is located, passes a few config files and outputs a log on the same folder. For example this would be the structure:

/home/user/application

And inside we have the following files:

script.sh      # this would be the script to launch
executablefile # this would be the file to run, it's called by the script as "./executable", since it's not in $PATH
config.json    # a config file for the executable that is passed by the script using arguments
logfile        # A log file written by the script, redirecting all Standard and Error output to the log file using tee

So if I CD into the folder and run the script, all is OK. But if I call this script from another location, it cannot locate the executable file and would most likely search for the config and output the log file on the location it was called from. This is not what I want.

So what changes could I write to the sh script. Something that establishes the script directory as the working directory when the script starts?

My main idea is to write a systemd service file which will call this script in the future.

Thank you.

2
  • How do you execute the script? Do you run /path/to/script.sh or bash /path/to/script.sh? – terdon Apr 18 '20 at 17:17
  • /path/to/script.sh I assume I would run it the same way from systemd. I think I found this solution: cd "${0%/*}" – alb2001 Apr 18 '20 at 17:51
0

There are two things you could do:

  1. Use absolute paths in your script. i.e. Change

    ./executablefile
    

    to

    /home/user/application/executablefile
    
  2. Set the working directory when you execute your script. You mentioned you wanted to make this a systemd unit. In that case, your service section could look like this:

    [Service]
    Type=forking
    ExecStart=/home/user/application/script.sh
    WorkingDirectory=/home/user/application
    

Also note, that a lot of the time, the things you would do in a startup script could be done by systemd. Things like environment variables, chrt, or affinities could all be done in the systemd configuration negating the need for a startup script.

Also, moving your executable to /usr/local/bin, making a writable space in /var for you log files and moving your json to /etc or ~/.config is generally good practice. If you are compiling executablefile, consider making command-line arguments to specify logfile and etcfile names.

1
  • Thank you! Didn't know that WorkingDirectory could be configured there in Systemd unit files. – alb2001 Apr 22 '20 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.