0

I'm going to mk a script that when you run it, it creates a html page with user's computer details... But I only have one problem... If the user put that script in a folder and set it as a cronjob, when the crontab execute it, the script makes a folder in home directory and that is bad, because, I want the script to make the folder with the HTML docs at the same dir that the script is... what can I do??

thnx ;-)

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Radwan
  • 33
  • 1
  • 6

5 Answers5

0

I would usually do the following:

#!/bin/bash
# sample script to change directory and save a file
WORKDIR=/home/file/n34_panda
cd $WORKDIR

echo "this "> newfile.txt

This is a simple answer without reviewing the rest of your code. To be honest the simplest method would be simply adding the command:

cd /path/to/html/docs

Then after that you can add the rest of your code

n34_panda
  • 2,577
  • 5
  • 24
  • 40
0

Try this script from several directories. It will always return its location.

#!/bin/bash

echo ${0%/*}
lanes
  • 1,847
  • 2
  • 19
  • 19
0

You can simply set cron as below :

# m h  dom mon dow   command
* * * * * cd /path-where-you-want-to-save/ && /path/of/yourscript.sh
Rahul Patil
  • 1,014
  • 3
  • 14
  • 30
0

As suggested in the comments, there are ways of a script knowing what directory it is stored in. However, I would recommend a simpler solution. Use absolute file paths in the script. The destination directory could be an argument to the script. This make the script more flexible; it means that you don't have to have many copies stored in separate directories if you want to do the same task in more than one place.

#!/bin/bash

output_dir="$1" # first argument to the script
echo "blah blah" > "$output_dir"/filename
Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

Using bash parameter expansion (https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) to extract the path from the special variable $0 (which stores the name of the script) if executed from a remote folder and the current directory otherwise ($0 will not contain full path if executed from current directory).

#!/bin/bash    
if [[ "$0" == */* ]]; then
  script_path=${0%/*}
else
  script_path=$(pwd)
fi

I am testing if the special variable $0 contains a /. if so then use parameter expansion to truncate everything following the last /. If it does not contain / then we must be in the current directory, so store the result of pwd.

From my testing this allowed me to get the same output if executed as /pathTo/script.sh or pushd /pathTo; ./script.sh; popd

I tested this in Cygwin with GNU bash, version 4.3.42

Richard Erickson
  • 2,568
  • 8
  • 26
  • 39
Michael H.
  • 146
  • 7